1 /*
   2  * Copyright (c) 2001, 2010, 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/heapRegionRemSet.hpp"
  32 #include "gc_implementation/shared/gcPolicyCounters.hpp"
  33 #include "runtime/arguments.hpp"
  34 #include "runtime/java.hpp"
  35 #include "runtime/mutexLocker.hpp"
  36 #include "utilities/debug.hpp"
  37 
  38 #define PREDICTIONS_VERBOSE 0
  39 
  40 // <NEW PREDICTION>
  41 
  42 // Different defaults for different number of GC threads
  43 // They were chosen by running GCOld and SPECjbb on debris with different
  44 //   numbers of GC threads and choosing them based on the results
  45 
  46 // all the same
  47 static double rs_length_diff_defaults[] = {
  48   0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
  49 };
  50 
  51 static double cost_per_card_ms_defaults[] = {
  52   0.01, 0.005, 0.005, 0.003, 0.003, 0.002, 0.002, 0.0015
  53 };
  54 
  55 // all the same
  56 static double fully_young_cards_per_entry_ratio_defaults[] = {
  57   1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
  58 };
  59 
  60 static double cost_per_entry_ms_defaults[] = {
  61   0.015, 0.01, 0.01, 0.008, 0.008, 0.0055, 0.0055, 0.005
  62 };
  63 
  64 static double cost_per_byte_ms_defaults[] = {
  65   0.00006, 0.00003, 0.00003, 0.000015, 0.000015, 0.00001, 0.00001, 0.000009
  66 };
  67 
  68 // these should be pretty consistent
  69 static double constant_other_time_ms_defaults[] = {
  70   5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0
  71 };
  72 
  73 
  74 static double young_other_cost_per_region_ms_defaults[] = {
  75   0.3, 0.2, 0.2, 0.15, 0.15, 0.12, 0.12, 0.1
  76 };
  77 
  78 static double non_young_other_cost_per_region_ms_defaults[] = {
  79   1.0, 0.7, 0.7, 0.5, 0.5, 0.42, 0.42, 0.30
  80 };
  81 
  82 // </NEW PREDICTION>
  83 
  84 G1CollectorPolicy::G1CollectorPolicy() :
  85   _parallel_gc_threads((ParallelGCThreads > 0) ? ParallelGCThreads : 1),
  86   _n_pauses(0),
  87   _recent_CH_strong_roots_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
  88   _recent_G1_strong_roots_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
  89   _recent_evac_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
  90   _recent_pause_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
  91   _recent_rs_sizes(new TruncatedSeq(NumPrevPausesForHeuristics)),
  92   _recent_gc_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
  93   _all_pause_times_ms(new NumberSeq()),
  94   _stop_world_start(0.0),
  95   _all_stop_world_times_ms(new NumberSeq()),
  96   _all_yield_times_ms(new NumberSeq()),
  97 
  98   _all_mod_union_times_ms(new NumberSeq()),
  99 
 100   _summary(new Summary()),
 101 
 102 #ifndef PRODUCT
 103   _cur_clear_ct_time_ms(0.0),
 104   _min_clear_cc_time_ms(-1.0),
 105   _max_clear_cc_time_ms(-1.0),
 106   _cur_clear_cc_time_ms(0.0),
 107   _cum_clear_cc_time_ms(0.0),
 108   _num_cc_clears(0L),
 109 #endif
 110 
 111   _region_num_young(0),
 112   _region_num_tenured(0),
 113   _prev_region_num_young(0),
 114   _prev_region_num_tenured(0),
 115 
 116   _aux_num(10),
 117   _all_aux_times_ms(new NumberSeq[_aux_num]),
 118   _cur_aux_start_times_ms(new double[_aux_num]),
 119   _cur_aux_times_ms(new double[_aux_num]),
 120   _cur_aux_times_set(new bool[_aux_num]),
 121 
 122   _concurrent_mark_init_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
 123   _concurrent_mark_remark_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
 124   _concurrent_mark_cleanup_times_ms(new TruncatedSeq(NumPrevPausesForHeuristics)),
 125 
 126   // <NEW PREDICTION>
 127 
 128   _alloc_rate_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 129   _prev_collection_pause_end_ms(0.0),
 130   _pending_card_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
 131   _rs_length_diff_seq(new TruncatedSeq(TruncatedSeqLength)),
 132   _cost_per_card_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 133   _fully_young_cards_per_entry_ratio_seq(new TruncatedSeq(TruncatedSeqLength)),
 134   _partially_young_cards_per_entry_ratio_seq(
 135                                          new TruncatedSeq(TruncatedSeqLength)),
 136   _cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 137   _partially_young_cost_per_entry_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 138   _cost_per_byte_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 139   _cost_per_byte_ms_during_cm_seq(new TruncatedSeq(TruncatedSeqLength)),
 140   _constant_other_time_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 141   _young_other_cost_per_region_ms_seq(new TruncatedSeq(TruncatedSeqLength)),
 142   _non_young_other_cost_per_region_ms_seq(
 143                                          new TruncatedSeq(TruncatedSeqLength)),
 144 
 145   _pending_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
 146   _scanned_cards_seq(new TruncatedSeq(TruncatedSeqLength)),
 147   _rs_lengths_seq(new TruncatedSeq(TruncatedSeqLength)),
 148 
 149   _pause_time_target_ms((double) MaxGCPauseMillis),
 150 
 151   // </NEW PREDICTION>
 152 
 153   _in_young_gc_mode(false),
 154   _full_young_gcs(true),
 155   _full_young_pause_num(0),
 156   _partial_young_pause_num(0),
 157 
 158   _during_marking(false),
 159   _in_marking_window(false),
 160   _in_marking_window_im(false),
 161 
 162   _known_garbage_ratio(0.0),
 163   _known_garbage_bytes(0),
 164 
 165   _young_gc_eff_seq(new TruncatedSeq(TruncatedSeqLength)),
 166 
 167    _recent_prev_end_times_for_all_gcs_sec(new TruncatedSeq(NumPrevPausesForHeuristics)),
 168 
 169   _recent_CS_bytes_used_before(new TruncatedSeq(NumPrevPausesForHeuristics)),
 170   _recent_CS_bytes_surviving(new TruncatedSeq(NumPrevPausesForHeuristics)),
 171 
 172   _recent_avg_pause_time_ratio(0.0),
 173   _num_markings(0),
 174   _n_marks(0),
 175   _n_pauses_at_mark_end(0),
 176 
 177   _all_full_gc_times_ms(new NumberSeq()),
 178 
 179   // G1PausesBtwnConcMark defaults to -1
 180   // so the hack is to do the cast  QQQ FIXME
 181   _pauses_btwn_concurrent_mark((size_t)G1PausesBtwnConcMark),
 182   _n_marks_since_last_pause(0),
 183   _initiate_conc_mark_if_possible(false),
 184   _during_initial_mark_pause(false),
 185   _should_revert_to_full_young_gcs(false),
 186   _last_full_young_gc(false),
 187 
 188   _prev_collection_pause_used_at_end_bytes(0),
 189 
 190   _collection_set(NULL),
 191   _collection_set_size(0),
 192   _collection_set_bytes_used_before(0),
 193 
 194   // Incremental CSet attributes
 195   _inc_cset_build_state(Inactive),
 196   _inc_cset_head(NULL),
 197   _inc_cset_tail(NULL),
 198   _inc_cset_size(0),
 199   _inc_cset_young_index(0),
 200   _inc_cset_bytes_used_before(0),
 201   _inc_cset_max_finger(NULL),
 202   _inc_cset_recorded_young_bytes(0),
 203   _inc_cset_recorded_rs_lengths(0),
 204   _inc_cset_predicted_elapsed_time_ms(0.0),
 205   _inc_cset_predicted_bytes_to_copy(0),
 206 
 207 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
 208 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 209 #endif // _MSC_VER
 210 
 211   _short_lived_surv_rate_group(new SurvRateGroup(this, "Short Lived",
 212                                                  G1YoungSurvRateNumRegionsSummary)),
 213   _survivor_surv_rate_group(new SurvRateGroup(this, "Survivor",
 214                                               G1YoungSurvRateNumRegionsSummary)),
 215   // add here any more surv rate groups
 216   _recorded_survivor_regions(0),
 217   _recorded_survivor_head(NULL),
 218   _recorded_survivor_tail(NULL),
 219   _survivors_age_table(true),
 220 
 221   _gc_overhead_perc(0.0)
 222 
 223 {
 224   // Set up the region size and associated fields. Given that the
 225   // policy is created before the heap, we have to set this up here,
 226   // so it's done as soon as possible.
 227   HeapRegion::setup_heap_region_size(Arguments::min_heap_size());
 228   HeapRegionRemSet::setup_remset_size();
 229 
 230   // Verify PLAB sizes
 231   const uint region_size = HeapRegion::GrainWords;
 232   if (YoungPLABSize > region_size || OldPLABSize > region_size) {
 233     char buffer[128];
 234     jio_snprintf(buffer, sizeof(buffer), "%sPLABSize should be at most %u",
 235                  OldPLABSize > region_size ? "Old" : "Young", region_size);
 236     vm_exit_during_initialization(buffer);
 237   }
 238 
 239   _recent_prev_end_times_for_all_gcs_sec->add(os::elapsedTime());
 240   _prev_collection_pause_end_ms = os::elapsedTime() * 1000.0;
 241 
 242   _par_last_gc_worker_start_times_ms = new double[_parallel_gc_threads];
 243   _par_last_ext_root_scan_times_ms = new double[_parallel_gc_threads];
 244   _par_last_mark_stack_scan_times_ms = new double[_parallel_gc_threads];
 245 
 246   _par_last_update_rs_times_ms = new double[_parallel_gc_threads];
 247   _par_last_update_rs_processed_buffers = new double[_parallel_gc_threads];
 248 
 249   _par_last_scan_rs_times_ms = new double[_parallel_gc_threads];
 250 
 251   _par_last_obj_copy_times_ms = new double[_parallel_gc_threads];
 252 
 253   _par_last_termination_times_ms = new double[_parallel_gc_threads];
 254   _par_last_termination_attempts = new double[_parallel_gc_threads];
 255   _par_last_gc_worker_end_times_ms = new double[_parallel_gc_threads];
 256 
 257   // start conservatively
 258   _expensive_region_limit_ms = 0.5 * (double) MaxGCPauseMillis;
 259 
 260   // <NEW PREDICTION>
 261 
 262   int index;
 263   if (ParallelGCThreads == 0)
 264     index = 0;
 265   else if (ParallelGCThreads > 8)
 266     index = 7;
 267   else
 268     index = ParallelGCThreads - 1;
 269 
 270   _pending_card_diff_seq->add(0.0);
 271   _rs_length_diff_seq->add(rs_length_diff_defaults[index]);
 272   _cost_per_card_ms_seq->add(cost_per_card_ms_defaults[index]);
 273   _fully_young_cards_per_entry_ratio_seq->add(
 274                             fully_young_cards_per_entry_ratio_defaults[index]);
 275   _cost_per_entry_ms_seq->add(cost_per_entry_ms_defaults[index]);
 276   _cost_per_byte_ms_seq->add(cost_per_byte_ms_defaults[index]);
 277   _constant_other_time_ms_seq->add(constant_other_time_ms_defaults[index]);
 278   _young_other_cost_per_region_ms_seq->add(
 279                                young_other_cost_per_region_ms_defaults[index]);
 280   _non_young_other_cost_per_region_ms_seq->add(
 281                            non_young_other_cost_per_region_ms_defaults[index]);
 282 
 283   // </NEW PREDICTION>
 284 
 285   // Below, we might need to calculate the pause time target based on
 286   // the pause interval. When we do so we are going to give G1 maximum
 287   // flexibility and allow it to do pauses when it needs to. So, we'll
 288   // arrange that the pause interval to be pause time target + 1 to
 289   // ensure that a) the pause time target is maximized with respect to
 290   // the pause interval and b) we maintain the invariant that pause
 291   // time target < pause interval. If the user does not want this
 292   // maximum flexibility, they will have to set the pause interval
 293   // explicitly.
 294 
 295   // First make sure that, if either parameter is set, its value is
 296   // reasonable.
 297   if (!FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
 298     if (MaxGCPauseMillis < 1) {
 299       vm_exit_during_initialization("MaxGCPauseMillis should be "
 300                                     "greater than 0");
 301     }
 302   }
 303   if (!FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
 304     if (GCPauseIntervalMillis < 1) {
 305       vm_exit_during_initialization("GCPauseIntervalMillis should be "
 306                                     "greater than 0");
 307     }
 308   }
 309 
 310   // Then, if the pause time target parameter was not set, set it to
 311   // the default value.
 312   if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
 313     if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
 314       // The default pause time target in G1 is 200ms
 315       FLAG_SET_DEFAULT(MaxGCPauseMillis, 200);
 316     } else {
 317       // We do not allow the pause interval to be set without the
 318       // pause time target
 319       vm_exit_during_initialization("GCPauseIntervalMillis cannot be set "
 320                                     "without setting MaxGCPauseMillis");
 321     }
 322   }
 323 
 324   // Then, if the interval parameter was not set, set it according to
 325   // the pause time target (this will also deal with the case when the
 326   // pause time target is the default value).
 327   if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
 328     FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);
 329   }
 330 
 331   // Finally, make sure that the two parameters are consistent.
 332   if (MaxGCPauseMillis >= GCPauseIntervalMillis) {
 333     char buffer[256];
 334     jio_snprintf(buffer, 256,
 335                  "MaxGCPauseMillis (%u) should be less than "
 336                  "GCPauseIntervalMillis (%u)",
 337                  MaxGCPauseMillis, GCPauseIntervalMillis);
 338     vm_exit_during_initialization(buffer);
 339   }
 340 
 341   double max_gc_time = (double) MaxGCPauseMillis / 1000.0;
 342   double time_slice  = (double) GCPauseIntervalMillis / 1000.0;
 343   _mmu_tracker = new G1MMUTrackerQueue(time_slice, max_gc_time);
 344   _sigma = (double) G1ConfidencePercent / 100.0;
 345 
 346   // start conservatively (around 50ms is about right)
 347   _concurrent_mark_init_times_ms->add(0.05);
 348   _concurrent_mark_remark_times_ms->add(0.05);
 349   _concurrent_mark_cleanup_times_ms->add(0.20);
 350   _tenuring_threshold = MaxTenuringThreshold;
 351 
 352   // if G1FixedSurvivorSpaceSize is 0 which means the size is not
 353   // fixed, then _max_survivor_regions will be calculated at
 354   // calculate_young_list_target_length during initialization
 355   _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
 356 
 357   assert(GCTimeRatio > 0,
 358          "we should have set it to a default value set_g1_gc_flags() "
 359          "if a user set it to 0");
 360   _gc_overhead_perc = 100.0 * (1.0 / (1.0 + GCTimeRatio));
 361 
 362   initialize_all();
 363 }
 364 
 365 // Increment "i", mod "len"
 366 static void inc_mod(int& i, int len) {
 367   i++; if (i == len) i = 0;
 368 }
 369 
 370 void G1CollectorPolicy::initialize_flags() {
 371   set_min_alignment(HeapRegion::GrainBytes);
 372   set_max_alignment(GenRemSet::max_alignment_constraint(rem_set_name()));
 373   if (SurvivorRatio < 1) {
 374     vm_exit_during_initialization("Invalid survivor ratio specified");
 375   }
 376   CollectorPolicy::initialize_flags();
 377 }
 378 
 379 // The easiest way to deal with the parsing of the NewSize /
 380 // MaxNewSize / etc. parameteres is to re-use the code in the
 381 // TwoGenerationCollectorPolicy class. This is similar to what
 382 // ParallelScavenge does with its GenerationSizer class (see
 383 // ParallelScavengeHeap::initialize()). We might change this in the
 384 // future, but it's a good start.
 385 class G1YoungGenSizer : public TwoGenerationCollectorPolicy {
 386   size_t size_to_region_num(size_t byte_size) {
 387     return MAX2((size_t) 1, byte_size / HeapRegion::GrainBytes);
 388   }
 389 
 390 public:
 391   G1YoungGenSizer() {
 392     initialize_flags();
 393     initialize_size_info();
 394   }
 395 
 396   size_t min_young_region_num() {
 397     return size_to_region_num(_min_gen0_size);
 398   }
 399   size_t initial_young_region_num() {
 400     return size_to_region_num(_initial_gen0_size);
 401   }
 402   size_t max_young_region_num() {
 403     return size_to_region_num(_max_gen0_size);
 404   }
 405 };
 406 
 407 void G1CollectorPolicy::init() {
 408   // Set aside an initial future to_space.
 409   _g1 = G1CollectedHeap::heap();
 410 
 411   assert(Heap_lock->owned_by_self(), "Locking discipline.");
 412 
 413   initialize_gc_policy_counters();
 414 
 415   if (G1Gen) {
 416     _in_young_gc_mode = true;
 417 
 418     G1YoungGenSizer sizer;
 419     size_t initial_region_num = sizer.initial_young_region_num();
 420 
 421     if (UseAdaptiveSizePolicy) {
 422       set_adaptive_young_list_length(true);
 423       _young_list_fixed_length = 0;
 424     } else {
 425       set_adaptive_young_list_length(false);
 426       _young_list_fixed_length = initial_region_num;
 427     }
 428     _free_regions_at_end_of_collection = _g1->free_regions();
 429     calculate_young_list_min_length();
 430     guarantee( _young_list_min_length == 0, "invariant, not enough info" );
 431     calculate_young_list_target_length();
 432   } else {
 433      _young_list_fixed_length = 0;
 434     _in_young_gc_mode = false;
 435   }
 436 
 437   // We may immediately start allocating regions and placing them on the
 438   // collection set list. Initialize the per-collection set info
 439   start_incremental_cset_building();
 440 }
 441 
 442 // Create the jstat counters for the policy.
 443 void G1CollectorPolicy::initialize_gc_policy_counters()
 444 {
 445   _gc_policy_counters = new GCPolicyCounters("GarbageFirst", 1, 2 + G1Gen);
 446 }
 447 
 448 void G1CollectorPolicy::calculate_young_list_min_length() {
 449   _young_list_min_length = 0;
 450 
 451   if (!adaptive_young_list_length())
 452     return;
 453 
 454   if (_alloc_rate_ms_seq->num() > 3) {
 455     double now_sec = os::elapsedTime();
 456     double when_ms = _mmu_tracker->when_max_gc_sec(now_sec) * 1000.0;
 457     double alloc_rate_ms = predict_alloc_rate_ms();
 458     int min_regions = (int) ceil(alloc_rate_ms * when_ms);
 459     int current_region_num = (int) _g1->young_list()->length();
 460     _young_list_min_length = min_regions + current_region_num;
 461   }
 462 }
 463 
 464 void G1CollectorPolicy::calculate_young_list_target_length() {
 465   if (adaptive_young_list_length()) {
 466     size_t rs_lengths = (size_t) get_new_prediction(_rs_lengths_seq);
 467     calculate_young_list_target_length(rs_lengths);
 468   } else {
 469     if (full_young_gcs())
 470       _young_list_target_length = _young_list_fixed_length;
 471     else
 472       _young_list_target_length = _young_list_fixed_length / 2;
 473 
 474     _young_list_target_length = MAX2(_young_list_target_length, (size_t)1);
 475   }
 476   calculate_survivors_policy();
 477 }
 478 
 479 void G1CollectorPolicy::calculate_young_list_target_length(size_t rs_lengths) {
 480   guarantee( adaptive_young_list_length(), "pre-condition" );
 481   guarantee( !_in_marking_window || !_last_full_young_gc, "invariant" );
 482 
 483   double start_time_sec = os::elapsedTime();
 484   size_t min_reserve_perc = MAX2((size_t)2, (size_t)G1ReservePercent);
 485   min_reserve_perc = MIN2((size_t) 50, min_reserve_perc);
 486   size_t reserve_regions =
 487     (size_t) ((double) min_reserve_perc * (double) _g1->n_regions() / 100.0);
 488 
 489   if (full_young_gcs() && _free_regions_at_end_of_collection > 0) {
 490     // we are in fully-young mode and there are free regions in the heap
 491 
 492     double survivor_regions_evac_time =
 493         predict_survivor_regions_evac_time();
 494 
 495     double target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
 496     size_t pending_cards = (size_t) get_new_prediction(_pending_cards_seq);
 497     size_t adj_rs_lengths = rs_lengths + predict_rs_length_diff();
 498     size_t scanned_cards = predict_young_card_num(adj_rs_lengths);
 499     double base_time_ms = predict_base_elapsed_time_ms(pending_cards, scanned_cards)
 500                           + survivor_regions_evac_time;
 501 
 502     // the result
 503     size_t final_young_length = 0;
 504 
 505     size_t init_free_regions =
 506       MAX2((size_t)0, _free_regions_at_end_of_collection - reserve_regions);
 507 
 508     // if we're still under the pause target...
 509     if (base_time_ms <= target_pause_time_ms) {
 510       // We make sure that the shortest young length that makes sense
 511       // fits within the target pause time.
 512       size_t min_young_length = 1;
 513 
 514       if (predict_will_fit(min_young_length, base_time_ms,
 515                                      init_free_regions, target_pause_time_ms)) {
 516         // The shortest young length will fit within the target pause time;
 517         // we'll now check whether the absolute maximum number of young
 518         // regions will fit in the target pause time. If not, we'll do
 519         // a binary search between min_young_length and max_young_length
 520         size_t abs_max_young_length = _free_regions_at_end_of_collection - 1;
 521         size_t max_young_length = abs_max_young_length;
 522 
 523         if (max_young_length > min_young_length) {
 524           // Let's check if the initial max young length will fit within the
 525           // target pause. If so then there is no need to search for a maximal
 526           // young length - we'll return the initial maximum
 527 
 528           if (predict_will_fit(max_young_length, base_time_ms,
 529                                 init_free_regions, target_pause_time_ms)) {
 530             // The maximum young length will satisfy the target pause time.
 531             // We are done so set min young length to this maximum length.
 532             // The code after the loop will then set final_young_length using
 533             // the value cached in the minimum length.
 534             min_young_length = max_young_length;
 535           } else {
 536             // The maximum possible number of young regions will not fit within
 537             // the target pause time so let's search....
 538 
 539             size_t diff = (max_young_length - min_young_length) / 2;
 540             max_young_length = min_young_length + diff;
 541 
 542             while (max_young_length > min_young_length) {
 543               if (predict_will_fit(max_young_length, base_time_ms,
 544                                         init_free_regions, target_pause_time_ms)) {
 545 
 546                 // The current max young length will fit within the target
 547                 // pause time. Note we do not exit the loop here. By setting
 548                 // min = max, and then increasing the max below means that
 549                 // we will continue searching for an upper bound in the
 550                 // range [max..max+diff]
 551                 min_young_length = max_young_length;
 552               }
 553               diff = (max_young_length - min_young_length) / 2;
 554               max_young_length = min_young_length + diff;
 555             }
 556             // the above loop found a maximal young length that will fit
 557             // within the target pause time.
 558           }
 559           assert(min_young_length <= abs_max_young_length, "just checking");
 560         }
 561         final_young_length = min_young_length;
 562       }
 563     }
 564     // and we're done!
 565 
 566     // we should have at least one region in the target young length
 567     _young_list_target_length =
 568         MAX2((size_t) 1, final_young_length + _recorded_survivor_regions);
 569 
 570     // let's keep an eye of how long we spend on this calculation
 571     // right now, I assume that we'll print it when we need it; we
 572     // should really adde it to the breakdown of a pause
 573     double end_time_sec = os::elapsedTime();
 574     double elapsed_time_ms = (end_time_sec - start_time_sec) * 1000.0;
 575 
 576 #ifdef TRACE_CALC_YOUNG_LENGTH
 577     // leave this in for debugging, just in case
 578     gclog_or_tty->print_cr("target = %1.1lf ms, young = " SIZE_FORMAT ", "
 579                            "elapsed %1.2lf ms, (%s%s) " SIZE_FORMAT SIZE_FORMAT,
 580                            target_pause_time_ms,
 581                            _young_list_target_length
 582                            elapsed_time_ms,
 583                            full_young_gcs() ? "full" : "partial",
 584                            during_initial_mark_pause() ? " i-m" : "",
 585                            _in_marking_window,
 586                            _in_marking_window_im);
 587 #endif // TRACE_CALC_YOUNG_LENGTH
 588 
 589     if (_young_list_target_length < _young_list_min_length) {
 590       // bummer; this means that, if we do a pause when the maximal
 591       // length dictates, we'll violate the pause spacing target (the
 592       // min length was calculate based on the application's current
 593       // alloc rate);
 594 
 595       // so, we have to bite the bullet, and allocate the minimum
 596       // number. We'll violate our target, but we just can't meet it.
 597 
 598 #ifdef TRACE_CALC_YOUNG_LENGTH
 599       // leave this in for debugging, just in case
 600       gclog_or_tty->print_cr("adjusted target length from "
 601                              SIZE_FORMAT " to " SIZE_FORMAT,
 602                              _young_list_target_length, _young_list_min_length);
 603 #endif // TRACE_CALC_YOUNG_LENGTH
 604 
 605       _young_list_target_length = _young_list_min_length;
 606     }
 607   } else {
 608     // we are in a partially-young mode or we've run out of regions (due
 609     // to evacuation failure)
 610 
 611 #ifdef TRACE_CALC_YOUNG_LENGTH
 612     // leave this in for debugging, just in case
 613     gclog_or_tty->print_cr("(partial) setting target to " SIZE_FORMAT
 614                            _young_list_min_length);
 615 #endif // TRACE_CALC_YOUNG_LENGTH
 616     // we'll do the pause as soon as possible by choosing the minimum
 617     _young_list_target_length =
 618       MAX2(_young_list_min_length, (size_t) 1);
 619   }
 620 
 621   _rs_lengths_prediction = rs_lengths;
 622 }
 623 
 624 // This is used by: calculate_young_list_target_length(rs_length). It
 625 // returns true iff:
 626 //   the predicted pause time for the given young list will not overflow
 627 //   the target pause time
 628 // and:
 629 //   the predicted amount of surviving data will not overflow the
 630 //   the amount of free space available for survivor regions.
 631 //
 632 bool
 633 G1CollectorPolicy::predict_will_fit(size_t young_length,
 634                                     double base_time_ms,
 635                                     size_t init_free_regions,
 636                                     double target_pause_time_ms) {
 637 
 638   if (young_length >= init_free_regions)
 639     // end condition 1: not enough space for the young regions
 640     return false;
 641 
 642   double accum_surv_rate_adj = 0.0;
 643   double accum_surv_rate =
 644     accum_yg_surv_rate_pred((int)(young_length - 1)) - accum_surv_rate_adj;
 645 
 646   size_t bytes_to_copy =
 647     (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
 648 
 649   double copy_time_ms = predict_object_copy_time_ms(bytes_to_copy);
 650 
 651   double young_other_time_ms =
 652                        predict_young_other_time_ms(young_length);
 653 
 654   double pause_time_ms =
 655                    base_time_ms + copy_time_ms + young_other_time_ms;
 656 
 657   if (pause_time_ms > target_pause_time_ms)
 658     // end condition 2: over the target pause time
 659     return false;
 660 
 661   size_t free_bytes =
 662                  (init_free_regions - young_length) * HeapRegion::GrainBytes;
 663 
 664   if ((2.0 + sigma()) * (double) bytes_to_copy > (double) free_bytes)
 665     // end condition 3: out of to-space (conservatively)
 666     return false;
 667 
 668   // success!
 669   return true;
 670 }
 671 
 672 double G1CollectorPolicy::predict_survivor_regions_evac_time() {
 673   double survivor_regions_evac_time = 0.0;
 674   for (HeapRegion * r = _recorded_survivor_head;
 675        r != NULL && r != _recorded_survivor_tail->get_next_young_region();
 676        r = r->get_next_young_region()) {
 677     survivor_regions_evac_time += predict_region_elapsed_time_ms(r, true);
 678   }
 679   return survivor_regions_evac_time;
 680 }
 681 
 682 void G1CollectorPolicy::check_prediction_validity() {
 683   guarantee( adaptive_young_list_length(), "should not call this otherwise" );
 684 
 685   size_t rs_lengths = _g1->young_list()->sampled_rs_lengths();
 686   if (rs_lengths > _rs_lengths_prediction) {
 687     // add 10% to avoid having to recalculate often
 688     size_t rs_lengths_prediction = rs_lengths * 1100 / 1000;
 689     calculate_young_list_target_length(rs_lengths_prediction);
 690   }
 691 }
 692 
 693 HeapWord* G1CollectorPolicy::mem_allocate_work(size_t size,
 694                                                bool is_tlab,
 695                                                bool* gc_overhead_limit_was_exceeded) {
 696   guarantee(false, "Not using this policy feature yet.");
 697   return NULL;
 698 }
 699 
 700 // This method controls how a collector handles one or more
 701 // of its generations being fully allocated.
 702 HeapWord* G1CollectorPolicy::satisfy_failed_allocation(size_t size,
 703                                                        bool is_tlab) {
 704   guarantee(false, "Not using this policy feature yet.");
 705   return NULL;
 706 }
 707 
 708 
 709 #ifndef PRODUCT
 710 bool G1CollectorPolicy::verify_young_ages() {
 711   HeapRegion* head = _g1->young_list()->first_region();
 712   return
 713     verify_young_ages(head, _short_lived_surv_rate_group);
 714   // also call verify_young_ages on any additional surv rate groups
 715 }
 716 
 717 bool
 718 G1CollectorPolicy::verify_young_ages(HeapRegion* head,
 719                                      SurvRateGroup *surv_rate_group) {
 720   guarantee( surv_rate_group != NULL, "pre-condition" );
 721 
 722   const char* name = surv_rate_group->name();
 723   bool ret = true;
 724   int prev_age = -1;
 725 
 726   for (HeapRegion* curr = head;
 727        curr != NULL;
 728        curr = curr->get_next_young_region()) {
 729     SurvRateGroup* group = curr->surv_rate_group();
 730     if (group == NULL && !curr->is_survivor()) {
 731       gclog_or_tty->print_cr("## %s: encountered NULL surv_rate_group", name);
 732       ret = false;
 733     }
 734 
 735     if (surv_rate_group == group) {
 736       int age = curr->age_in_surv_rate_group();
 737 
 738       if (age < 0) {
 739         gclog_or_tty->print_cr("## %s: encountered negative age", name);
 740         ret = false;
 741       }
 742 
 743       if (age <= prev_age) {
 744         gclog_or_tty->print_cr("## %s: region ages are not strictly increasing "
 745                                "(%d, %d)", name, age, prev_age);
 746         ret = false;
 747       }
 748       prev_age = age;
 749     }
 750   }
 751 
 752   return ret;
 753 }
 754 #endif // PRODUCT
 755 
 756 void G1CollectorPolicy::record_full_collection_start() {
 757   _cur_collection_start_sec = os::elapsedTime();
 758   // Release the future to-space so that it is available for compaction into.
 759   _g1->set_full_collection();
 760 }
 761 
 762 void G1CollectorPolicy::record_full_collection_end() {
 763   // Consider this like a collection pause for the purposes of allocation
 764   // since last pause.
 765   double end_sec = os::elapsedTime();
 766   double full_gc_time_sec = end_sec - _cur_collection_start_sec;
 767   double full_gc_time_ms = full_gc_time_sec * 1000.0;
 768 
 769   _all_full_gc_times_ms->add(full_gc_time_ms);
 770 
 771   update_recent_gc_times(end_sec, full_gc_time_ms);
 772 
 773   _g1->clear_full_collection();
 774 
 775   // "Nuke" the heuristics that control the fully/partially young GC
 776   // transitions and make sure we start with fully young GCs after the
 777   // Full GC.
 778   set_full_young_gcs(true);
 779   _last_full_young_gc = false;
 780   _should_revert_to_full_young_gcs = false;
 781   clear_initiate_conc_mark_if_possible();
 782   clear_during_initial_mark_pause();
 783   _known_garbage_bytes = 0;
 784   _known_garbage_ratio = 0.0;
 785   _in_marking_window = false;
 786   _in_marking_window_im = false;
 787 
 788   _short_lived_surv_rate_group->start_adding_regions();
 789   // also call this on any additional surv rate groups
 790 
 791   record_survivor_regions(0, NULL, NULL);
 792 
 793   _prev_region_num_young   = _region_num_young;
 794   _prev_region_num_tenured = _region_num_tenured;
 795 
 796   _free_regions_at_end_of_collection = _g1->free_regions();
 797   // Reset survivors SurvRateGroup.
 798   _survivor_surv_rate_group->reset();
 799   calculate_young_list_min_length();
 800   calculate_young_list_target_length();
 801  }
 802 
 803 void G1CollectorPolicy::record_before_bytes(size_t bytes) {
 804   _bytes_in_to_space_before_gc += bytes;
 805 }
 806 
 807 void G1CollectorPolicy::record_after_bytes(size_t bytes) {
 808   _bytes_in_to_space_after_gc += bytes;
 809 }
 810 
 811 void G1CollectorPolicy::record_stop_world_start() {
 812   _stop_world_start = os::elapsedTime();
 813 }
 814 
 815 void G1CollectorPolicy::record_collection_pause_start(double start_time_sec,
 816                                                       size_t start_used) {
 817   if (PrintGCDetails) {
 818     gclog_or_tty->stamp(PrintGCTimeStamps);
 819     gclog_or_tty->print("[GC pause");
 820     if (in_young_gc_mode())
 821       gclog_or_tty->print(" (%s)", full_young_gcs() ? "young" : "partial");
 822   }
 823 
 824   assert(_g1->used_regions() == _g1->recalculate_used_regions(),
 825          "sanity");
 826   assert(_g1->used() == _g1->recalculate_used(), "sanity");
 827 
 828   double s_w_t_ms = (start_time_sec - _stop_world_start) * 1000.0;
 829   _all_stop_world_times_ms->add(s_w_t_ms);
 830   _stop_world_start = 0.0;
 831 
 832   _cur_collection_start_sec = start_time_sec;
 833   _cur_collection_pause_used_at_start_bytes = start_used;
 834   _cur_collection_pause_used_regions_at_start = _g1->used_regions();
 835   _pending_cards = _g1->pending_card_num();
 836   _max_pending_cards = _g1->max_pending_card_num();
 837 
 838   _bytes_in_to_space_before_gc = 0;
 839   _bytes_in_to_space_after_gc = 0;
 840   _bytes_in_collection_set_before_gc = 0;
 841 
 842 #ifdef DEBUG
 843   // initialise these to something well known so that we can spot
 844   // if they are not set properly
 845 
 846   for (int i = 0; i < _parallel_gc_threads; ++i) {
 847     _par_last_gc_worker_start_times_ms[i] = -1234.0;
 848     _par_last_ext_root_scan_times_ms[i] = -1234.0;
 849     _par_last_mark_stack_scan_times_ms[i] = -1234.0;
 850     _par_last_update_rs_times_ms[i] = -1234.0;
 851     _par_last_update_rs_processed_buffers[i] = -1234.0;
 852     _par_last_scan_rs_times_ms[i] = -1234.0;
 853     _par_last_obj_copy_times_ms[i] = -1234.0;
 854     _par_last_termination_times_ms[i] = -1234.0;
 855     _par_last_termination_attempts[i] = -1234.0;
 856     _par_last_gc_worker_end_times_ms[i] = -1234.0;
 857   }
 858 #endif
 859 
 860   for (int i = 0; i < _aux_num; ++i) {
 861     _cur_aux_times_ms[i] = 0.0;
 862     _cur_aux_times_set[i] = false;
 863   }
 864 
 865   _satb_drain_time_set = false;
 866   _last_satb_drain_processed_buffers = -1;
 867 
 868   if (in_young_gc_mode())
 869     _last_young_gc_full = false;
 870 
 871   // do that for any other surv rate groups
 872   _short_lived_surv_rate_group->stop_adding_regions();
 873   _survivors_age_table.clear();
 874 
 875   assert( verify_young_ages(), "region age verification" );
 876 }
 877 
 878 void G1CollectorPolicy::record_mark_closure_time(double mark_closure_time_ms) {
 879   _mark_closure_time_ms = mark_closure_time_ms;
 880 }
 881 
 882 void G1CollectorPolicy::record_concurrent_mark_init_start() {
 883   _mark_init_start_sec = os::elapsedTime();
 884   guarantee(!in_young_gc_mode(), "should not do be here in young GC mode");
 885 }
 886 
 887 void G1CollectorPolicy::record_concurrent_mark_init_end_pre(double
 888                                                    mark_init_elapsed_time_ms) {
 889   _during_marking = true;
 890   assert(!initiate_conc_mark_if_possible(), "we should have cleared it by now");
 891   clear_during_initial_mark_pause();
 892   _cur_mark_stop_world_time_ms = mark_init_elapsed_time_ms;
 893 }
 894 
 895 void G1CollectorPolicy::record_concurrent_mark_init_end() {
 896   double end_time_sec = os::elapsedTime();
 897   double elapsed_time_ms = (end_time_sec - _mark_init_start_sec) * 1000.0;
 898   _concurrent_mark_init_times_ms->add(elapsed_time_ms);
 899   record_concurrent_mark_init_end_pre(elapsed_time_ms);
 900 
 901   _mmu_tracker->add_pause(_mark_init_start_sec, end_time_sec, true);
 902 }
 903 
 904 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
 905   _mark_remark_start_sec = os::elapsedTime();
 906   _during_marking = false;
 907 }
 908 
 909 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
 910   double end_time_sec = os::elapsedTime();
 911   double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
 912   _concurrent_mark_remark_times_ms->add(elapsed_time_ms);
 913   _cur_mark_stop_world_time_ms += elapsed_time_ms;
 914   _prev_collection_pause_end_ms += elapsed_time_ms;
 915 
 916   _mmu_tracker->add_pause(_mark_remark_start_sec, end_time_sec, true);
 917 }
 918 
 919 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
 920   _mark_cleanup_start_sec = os::elapsedTime();
 921 }
 922 
 923 void
 924 G1CollectorPolicy::record_concurrent_mark_cleanup_end(size_t freed_bytes,
 925                                                       size_t max_live_bytes) {
 926   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
 927   record_concurrent_mark_cleanup_end_work2();
 928 }
 929 
 930 void
 931 G1CollectorPolicy::
 932 record_concurrent_mark_cleanup_end_work1(size_t freed_bytes,
 933                                          size_t max_live_bytes) {
 934   if (_n_marks < 2) _n_marks++;
 935   if (G1PolicyVerbose > 0)
 936     gclog_or_tty->print_cr("At end of marking, max_live is " SIZE_FORMAT " MB "
 937                            " (of " SIZE_FORMAT " MB heap).",
 938                            max_live_bytes/M, _g1->capacity()/M);
 939 }
 940 
 941 // The important thing about this is that it includes "os::elapsedTime".
 942 void G1CollectorPolicy::record_concurrent_mark_cleanup_end_work2() {
 943   double end_time_sec = os::elapsedTime();
 944   double elapsed_time_ms = (end_time_sec - _mark_cleanup_start_sec)*1000.0;
 945   _concurrent_mark_cleanup_times_ms->add(elapsed_time_ms);
 946   _cur_mark_stop_world_time_ms += elapsed_time_ms;
 947   _prev_collection_pause_end_ms += elapsed_time_ms;
 948 
 949   _mmu_tracker->add_pause(_mark_cleanup_start_sec, end_time_sec, true);
 950 
 951   _num_markings++;
 952 
 953   // We did a marking, so reset the "since_last_mark" variables.
 954   double considerConcMarkCost = 1.0;
 955   // If there are available processors, concurrent activity is free...
 956   if (Threads::number_of_non_daemon_threads() * 2 <
 957       os::active_processor_count()) {
 958     considerConcMarkCost = 0.0;
 959   }
 960   _n_pauses_at_mark_end = _n_pauses;
 961   _n_marks_since_last_pause++;
 962 }
 963 
 964 void
 965 G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
 966   if (in_young_gc_mode()) {
 967     _should_revert_to_full_young_gcs = false;
 968     _last_full_young_gc = true;
 969     _in_marking_window = false;
 970     if (adaptive_young_list_length())
 971       calculate_young_list_target_length();
 972   }
 973 }
 974 
 975 void G1CollectorPolicy::record_concurrent_pause() {
 976   if (_stop_world_start > 0.0) {
 977     double yield_ms = (os::elapsedTime() - _stop_world_start) * 1000.0;
 978     _all_yield_times_ms->add(yield_ms);
 979   }
 980 }
 981 
 982 void G1CollectorPolicy::record_concurrent_pause_end() {
 983 }
 984 
 985 void G1CollectorPolicy::record_collection_pause_end_CH_strong_roots() {
 986   _cur_CH_strong_roots_end_sec = os::elapsedTime();
 987   _cur_CH_strong_roots_dur_ms =
 988     (_cur_CH_strong_roots_end_sec - _cur_collection_start_sec) * 1000.0;
 989 }
 990 
 991 void G1CollectorPolicy::record_collection_pause_end_G1_strong_roots() {
 992   _cur_G1_strong_roots_end_sec = os::elapsedTime();
 993   _cur_G1_strong_roots_dur_ms =
 994     (_cur_G1_strong_roots_end_sec - _cur_CH_strong_roots_end_sec) * 1000.0;
 995 }
 996 
 997 template<class T>
 998 T sum_of(T* sum_arr, int start, int n, int N) {
 999   T sum = (T)0;
1000   for (int i = 0; i < n; i++) {
1001     int j = (start + i) % N;
1002     sum += sum_arr[j];
1003   }
1004   return sum;
1005 }
1006 
1007 void G1CollectorPolicy::print_par_stats(int level,
1008                                         const char* str,
1009                                         double* data,
1010                                          bool summary) {
1011   double min = data[0], max = data[0];
1012   double total = 0.0;
1013   int j;
1014   for (j = 0; j < level; ++j)
1015     gclog_or_tty->print("   ");
1016   gclog_or_tty->print("[%s (ms):", str);
1017   for (uint i = 0; i < ParallelGCThreads; ++i) {
1018     double val = data[i];
1019     if (val < min)
1020       min = val;
1021     if (val > max)
1022       max = val;
1023     total += val;
1024     gclog_or_tty->print("  %3.1lf", val);
1025   }
1026   if (summary) {
1027     gclog_or_tty->print_cr("");
1028     double avg = total / (double) ParallelGCThreads;
1029     gclog_or_tty->print(" ");
1030     for (j = 0; j < level; ++j)
1031       gclog_or_tty->print("   ");
1032     gclog_or_tty->print("Avg: %5.1lf, Min: %5.1lf, Max: %5.1lf",
1033                         avg, min, max);
1034   }
1035   gclog_or_tty->print_cr("]");
1036 }
1037 
1038 void G1CollectorPolicy::print_par_sizes(int level,
1039                                         const char* str,
1040                                         double* data,
1041                                         bool summary) {
1042   double min = data[0], max = data[0];
1043   double total = 0.0;
1044   int j;
1045   for (j = 0; j < level; ++j)
1046     gclog_or_tty->print("   ");
1047   gclog_or_tty->print("[%s :", str);
1048   for (uint i = 0; i < ParallelGCThreads; ++i) {
1049     double val = data[i];
1050     if (val < min)
1051       min = val;
1052     if (val > max)
1053       max = val;
1054     total += val;
1055     gclog_or_tty->print(" %d", (int) val);
1056   }
1057   if (summary) {
1058     gclog_or_tty->print_cr("");
1059     double avg = total / (double) ParallelGCThreads;
1060     gclog_or_tty->print(" ");
1061     for (j = 0; j < level; ++j)
1062       gclog_or_tty->print("   ");
1063     gclog_or_tty->print("Sum: %d, Avg: %d, Min: %d, Max: %d",
1064                (int)total, (int)avg, (int)min, (int)max);
1065   }
1066   gclog_or_tty->print_cr("]");
1067 }
1068 
1069 void G1CollectorPolicy::print_stats (int level,
1070                                      const char* str,
1071                                      double value) {
1072   for (int j = 0; j < level; ++j)
1073     gclog_or_tty->print("   ");
1074   gclog_or_tty->print_cr("[%s: %5.1lf ms]", str, value);
1075 }
1076 
1077 void G1CollectorPolicy::print_stats (int level,
1078                                      const char* str,
1079                                      int value) {
1080   for (int j = 0; j < level; ++j)
1081     gclog_or_tty->print("   ");
1082   gclog_or_tty->print_cr("[%s: %d]", str, value);
1083 }
1084 
1085 double G1CollectorPolicy::avg_value (double* data) {
1086   if (ParallelGCThreads > 0) {
1087     double ret = 0.0;
1088     for (uint i = 0; i < ParallelGCThreads; ++i)
1089       ret += data[i];
1090     return ret / (double) ParallelGCThreads;
1091   } else {
1092     return data[0];
1093   }
1094 }
1095 
1096 double G1CollectorPolicy::max_value (double* data) {
1097   if (ParallelGCThreads > 0) {
1098     double ret = data[0];
1099     for (uint i = 1; i < ParallelGCThreads; ++i)
1100       if (data[i] > ret)
1101         ret = data[i];
1102     return ret;
1103   } else {
1104     return data[0];
1105   }
1106 }
1107 
1108 double G1CollectorPolicy::sum_of_values (double* data) {
1109   if (ParallelGCThreads > 0) {
1110     double sum = 0.0;
1111     for (uint i = 0; i < ParallelGCThreads; i++)
1112       sum += data[i];
1113     return sum;
1114   } else {
1115     return data[0];
1116   }
1117 }
1118 
1119 double G1CollectorPolicy::max_sum (double* data1,
1120                                    double* data2) {
1121   double ret = data1[0] + data2[0];
1122 
1123   if (ParallelGCThreads > 0) {
1124     for (uint i = 1; i < ParallelGCThreads; ++i) {
1125       double data = data1[i] + data2[i];
1126       if (data > ret)
1127         ret = data;
1128     }
1129   }
1130   return ret;
1131 }
1132 
1133 // Anything below that is considered to be zero
1134 #define MIN_TIMER_GRANULARITY 0.0000001
1135 
1136 void G1CollectorPolicy::record_collection_pause_end() {
1137   double end_time_sec = os::elapsedTime();
1138   double elapsed_ms = _last_pause_time_ms;
1139   bool parallel = ParallelGCThreads > 0;
1140   double evac_ms = (end_time_sec - _cur_G1_strong_roots_end_sec) * 1000.0;
1141   size_t rs_size =
1142     _cur_collection_pause_used_regions_at_start - collection_set_size();
1143   size_t cur_used_bytes = _g1->used();
1144   assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
1145   bool last_pause_included_initial_mark = false;
1146   bool update_stats = !_g1->evacuation_failed();
1147 
1148 #ifndef PRODUCT
1149   if (G1YoungSurvRateVerbose) {
1150     gclog_or_tty->print_cr("");
1151     _short_lived_surv_rate_group->print();
1152     // do that for any other surv rate groups too
1153   }
1154 #endif // PRODUCT
1155 
1156   if (in_young_gc_mode()) {
1157     last_pause_included_initial_mark = during_initial_mark_pause();
1158     if (last_pause_included_initial_mark)
1159       record_concurrent_mark_init_end_pre(0.0);
1160 
1161     size_t min_used_targ =
1162       (_g1->capacity() / 100) * InitiatingHeapOccupancyPercent;
1163 
1164 
1165     if (!_g1->mark_in_progress() && !_last_full_young_gc) {
1166       assert(!last_pause_included_initial_mark, "invariant");
1167       if (cur_used_bytes > min_used_targ &&
1168           cur_used_bytes > _prev_collection_pause_used_at_end_bytes) {
1169         assert(!during_initial_mark_pause(), "we should not see this here");
1170 
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 
1178     _prev_collection_pause_used_at_end_bytes = cur_used_bytes;
1179   }
1180 
1181   _mmu_tracker->add_pause(end_time_sec - elapsed_ms/1000.0,
1182                           end_time_sec, false);
1183 
1184   guarantee(_cur_collection_pause_used_regions_at_start >=
1185             collection_set_size(),
1186             "Negative RS size?");
1187 
1188   // This assert is exempted when we're doing parallel collection pauses,
1189   // because the fragmentation caused by the parallel GC allocation buffers
1190   // can lead to more memory being used during collection than was used
1191   // before. Best leave this out until the fragmentation problem is fixed.
1192   // Pauses in which evacuation failed can also lead to negative
1193   // collections, since no space is reclaimed from a region containing an
1194   // object whose evacuation failed.
1195   // Further, we're now always doing parallel collection.  But I'm still
1196   // leaving this here as a placeholder for a more precise assertion later.
1197   // (DLD, 10/05.)
1198   assert((true || parallel) // Always using GC LABs now.
1199          || _g1->evacuation_failed()
1200          || _cur_collection_pause_used_at_start_bytes >= cur_used_bytes,
1201          "Negative collection");
1202 
1203   size_t freed_bytes =
1204     _cur_collection_pause_used_at_start_bytes - cur_used_bytes;
1205   size_t surviving_bytes = _collection_set_bytes_used_before - freed_bytes;
1206 
1207   double survival_fraction =
1208     (double)surviving_bytes/
1209     (double)_collection_set_bytes_used_before;
1210 
1211   _n_pauses++;
1212 
1213   if (update_stats) {
1214     _recent_CH_strong_roots_times_ms->add(_cur_CH_strong_roots_dur_ms);
1215     _recent_G1_strong_roots_times_ms->add(_cur_G1_strong_roots_dur_ms);
1216     _recent_evac_times_ms->add(evac_ms);
1217     _recent_pause_times_ms->add(elapsed_ms);
1218 
1219     _recent_rs_sizes->add(rs_size);
1220 
1221     // We exempt parallel collection from this check because Alloc Buffer
1222     // fragmentation can produce negative collections.  Same with evac
1223     // failure.
1224     // Further, we're now always doing parallel collection.  But I'm still
1225     // leaving this here as a placeholder for a more precise assertion later.
1226     // (DLD, 10/05.
1227     assert((true || parallel)
1228            || _g1->evacuation_failed()
1229            || surviving_bytes <= _collection_set_bytes_used_before,
1230            "Or else negative collection!");
1231     _recent_CS_bytes_used_before->add(_collection_set_bytes_used_before);
1232     _recent_CS_bytes_surviving->add(surviving_bytes);
1233 
1234     // this is where we update the allocation rate of the application
1235     double app_time_ms =
1236       (_cur_collection_start_sec * 1000.0 - _prev_collection_pause_end_ms);
1237     if (app_time_ms < MIN_TIMER_GRANULARITY) {
1238       // This usually happens due to the timer not having the required
1239       // granularity. Some Linuxes are the usual culprits.
1240       // We'll just set it to something (arbitrarily) small.
1241       app_time_ms = 1.0;
1242     }
1243     size_t regions_allocated =
1244       (_region_num_young - _prev_region_num_young) +
1245       (_region_num_tenured - _prev_region_num_tenured);
1246     double alloc_rate_ms = (double) regions_allocated / app_time_ms;
1247     _alloc_rate_ms_seq->add(alloc_rate_ms);
1248     _prev_region_num_young   = _region_num_young;
1249     _prev_region_num_tenured = _region_num_tenured;
1250 
1251     double interval_ms =
1252       (end_time_sec - _recent_prev_end_times_for_all_gcs_sec->oldest()) * 1000.0;
1253     update_recent_gc_times(end_time_sec, elapsed_ms);
1254     _recent_avg_pause_time_ratio = _recent_gc_times_ms->sum()/interval_ms;
1255     if (recent_avg_pause_time_ratio() < 0.0 ||
1256         (recent_avg_pause_time_ratio() - 1.0 > 0.0)) {
1257 #ifndef PRODUCT
1258       // Dump info to allow post-facto debugging
1259       gclog_or_tty->print_cr("recent_avg_pause_time_ratio() out of bounds");
1260       gclog_or_tty->print_cr("-------------------------------------------");
1261       gclog_or_tty->print_cr("Recent GC Times (ms):");
1262       _recent_gc_times_ms->dump();
1263       gclog_or_tty->print_cr("(End Time=%3.3f) Recent GC End Times (s):", end_time_sec);
1264       _recent_prev_end_times_for_all_gcs_sec->dump();
1265       gclog_or_tty->print_cr("GC = %3.3f, Interval = %3.3f, Ratio = %3.3f",
1266                              _recent_gc_times_ms->sum(), interval_ms, recent_avg_pause_time_ratio());
1267       // In debug mode, terminate the JVM if the user wants to debug at this point.
1268       assert(!G1FailOnFPError, "Debugging data for CR 6898948 has been dumped above");
1269 #endif  // !PRODUCT
1270       // Clip ratio between 0.0 and 1.0, and continue. This will be fixed in
1271       // CR 6902692 by redoing the manner in which the ratio is incrementally computed.
1272       if (_recent_avg_pause_time_ratio < 0.0) {
1273         _recent_avg_pause_time_ratio = 0.0;
1274       } else {
1275         assert(_recent_avg_pause_time_ratio - 1.0 > 0.0, "Ctl-point invariant");
1276         _recent_avg_pause_time_ratio = 1.0;
1277       }
1278     }
1279   }
1280 
1281   if (G1PolicyVerbose > 1) {
1282     gclog_or_tty->print_cr("   Recording collection pause(%d)", _n_pauses);
1283   }
1284 
1285   PauseSummary* summary = _summary;
1286 
1287   double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
1288   double mark_stack_scan_time = avg_value(_par_last_mark_stack_scan_times_ms);
1289   double update_rs_time = avg_value(_par_last_update_rs_times_ms);
1290   double update_rs_processed_buffers =
1291     sum_of_values(_par_last_update_rs_processed_buffers);
1292   double scan_rs_time = avg_value(_par_last_scan_rs_times_ms);
1293   double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
1294   double termination_time = avg_value(_par_last_termination_times_ms);
1295 
1296   double parallel_other_time = _cur_collection_par_time_ms -
1297     (update_rs_time + ext_root_scan_time + mark_stack_scan_time +
1298      scan_rs_time + obj_copy_time + termination_time);
1299   if (update_stats) {
1300     MainBodySummary* body_summary = summary->main_body_summary();
1301     guarantee(body_summary != NULL, "should not be null!");
1302 
1303     if (_satb_drain_time_set)
1304       body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
1305     else
1306       body_summary->record_satb_drain_time_ms(0.0);
1307     body_summary->record_ext_root_scan_time_ms(ext_root_scan_time);
1308     body_summary->record_mark_stack_scan_time_ms(mark_stack_scan_time);
1309     body_summary->record_update_rs_time_ms(update_rs_time);
1310     body_summary->record_scan_rs_time_ms(scan_rs_time);
1311     body_summary->record_obj_copy_time_ms(obj_copy_time);
1312     if (parallel) {
1313       body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
1314       body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
1315       body_summary->record_termination_time_ms(termination_time);
1316       body_summary->record_parallel_other_time_ms(parallel_other_time);
1317     }
1318     body_summary->record_mark_closure_time_ms(_mark_closure_time_ms);
1319   }
1320 
1321   if (G1PolicyVerbose > 1) {
1322     gclog_or_tty->print_cr("      ET: %10.6f ms           (avg: %10.6f ms)\n"
1323                            "        CH Strong: %10.6f ms    (avg: %10.6f ms)\n"
1324                            "        G1 Strong: %10.6f ms    (avg: %10.6f ms)\n"
1325                            "        Evac:      %10.6f ms    (avg: %10.6f ms)\n"
1326                            "       ET-RS:  %10.6f ms      (avg: %10.6f ms)\n"
1327                            "      |RS|: " SIZE_FORMAT,
1328                            elapsed_ms, recent_avg_time_for_pauses_ms(),
1329                            _cur_CH_strong_roots_dur_ms, recent_avg_time_for_CH_strong_ms(),
1330                            _cur_G1_strong_roots_dur_ms, recent_avg_time_for_G1_strong_ms(),
1331                            evac_ms, recent_avg_time_for_evac_ms(),
1332                            scan_rs_time,
1333                            recent_avg_time_for_pauses_ms() -
1334                            recent_avg_time_for_G1_strong_ms(),
1335                            rs_size);
1336 
1337     gclog_or_tty->print_cr("       Used at start: " SIZE_FORMAT"K"
1338                            "       At end " SIZE_FORMAT "K\n"
1339                            "       garbage      : " SIZE_FORMAT "K"
1340                            "       of     " SIZE_FORMAT "K\n"
1341                            "       survival     : %6.2f%%  (%6.2f%% avg)",
1342                            _cur_collection_pause_used_at_start_bytes/K,
1343                            _g1->used()/K, freed_bytes/K,
1344                            _collection_set_bytes_used_before/K,
1345                            survival_fraction*100.0,
1346                            recent_avg_survival_fraction()*100.0);
1347     gclog_or_tty->print_cr("       Recent %% gc pause time: %6.2f",
1348                            recent_avg_pause_time_ratio() * 100.0);
1349   }
1350 
1351   double other_time_ms = elapsed_ms;
1352 
1353   if (_satb_drain_time_set) {
1354     other_time_ms -= _cur_satb_drain_time_ms;
1355   }
1356 
1357   if (parallel) {
1358     other_time_ms -= _cur_collection_par_time_ms + _cur_clear_ct_time_ms;
1359   } else {
1360     other_time_ms -=
1361       update_rs_time +
1362       ext_root_scan_time + mark_stack_scan_time +
1363       scan_rs_time + obj_copy_time;
1364   }
1365 
1366   if (PrintGCDetails) {
1367     gclog_or_tty->print_cr("%s, %1.8lf secs]",
1368                            (last_pause_included_initial_mark) ? " (initial-mark)" : "",
1369                            elapsed_ms / 1000.0);
1370 
1371     if (_satb_drain_time_set) {
1372       print_stats(1, "SATB Drain Time", _cur_satb_drain_time_ms);
1373     }
1374     if (_last_satb_drain_processed_buffers >= 0) {
1375       print_stats(2, "Processed Buffers", _last_satb_drain_processed_buffers);
1376     }
1377     if (parallel) {
1378       print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
1379       print_par_stats(2, "GC Worker Start Time",
1380                       _par_last_gc_worker_start_times_ms, false);
1381       print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
1382       print_par_sizes(3, "Processed Buffers",
1383                       _par_last_update_rs_processed_buffers, true);
1384       print_par_stats(2, "Ext Root Scanning",
1385                       _par_last_ext_root_scan_times_ms);
1386       print_par_stats(2, "Mark Stack Scanning",
1387                       _par_last_mark_stack_scan_times_ms);
1388       print_par_stats(2, "Scan RS", _par_last_scan_rs_times_ms);
1389       print_par_stats(2, "Object Copy", _par_last_obj_copy_times_ms);
1390       print_par_stats(2, "Termination", _par_last_termination_times_ms);
1391       print_par_sizes(3, "Termination Attempts",
1392                       _par_last_termination_attempts, true);
1393       print_par_stats(2, "GC Worker End Time",
1394                       _par_last_gc_worker_end_times_ms, false);
1395       print_stats(2, "Other", parallel_other_time);
1396       print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
1397     } else {
1398       print_stats(1, "Update RS", update_rs_time);
1399       print_stats(2, "Processed Buffers",
1400                   (int)update_rs_processed_buffers);
1401       print_stats(1, "Ext Root Scanning", ext_root_scan_time);
1402       print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
1403       print_stats(1, "Scan RS", scan_rs_time);
1404       print_stats(1, "Object Copying", obj_copy_time);
1405     }
1406 #ifndef PRODUCT
1407     print_stats(1, "Cur Clear CC", _cur_clear_cc_time_ms);
1408     print_stats(1, "Cum Clear CC", _cum_clear_cc_time_ms);
1409     print_stats(1, "Min Clear CC", _min_clear_cc_time_ms);
1410     print_stats(1, "Max Clear CC", _max_clear_cc_time_ms);
1411     if (_num_cc_clears > 0) {
1412       print_stats(1, "Avg Clear CC", _cum_clear_cc_time_ms / ((double)_num_cc_clears));
1413     }
1414 #endif
1415     print_stats(1, "Other", other_time_ms);
1416     print_stats(2, "Choose CSet", _recorded_young_cset_choice_time_ms);
1417 
1418     for (int i = 0; i < _aux_num; ++i) {
1419       if (_cur_aux_times_set[i]) {
1420         char buffer[96];
1421         sprintf(buffer, "Aux%d", i);
1422         print_stats(1, buffer, _cur_aux_times_ms[i]);
1423       }
1424     }
1425   }
1426   if (PrintGCDetails)
1427     gclog_or_tty->print("   [");
1428   if (PrintGC || PrintGCDetails)
1429     _g1->print_size_transition(gclog_or_tty,
1430                                _cur_collection_pause_used_at_start_bytes,
1431                                _g1->used(), _g1->capacity());
1432   if (PrintGCDetails)
1433     gclog_or_tty->print_cr("]");
1434 
1435   _all_pause_times_ms->add(elapsed_ms);
1436   if (update_stats) {
1437     summary->record_total_time_ms(elapsed_ms);
1438     summary->record_other_time_ms(other_time_ms);
1439   }
1440   for (int i = 0; i < _aux_num; ++i)
1441     if (_cur_aux_times_set[i])
1442       _all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
1443 
1444   // Reset marks-between-pauses counter.
1445   _n_marks_since_last_pause = 0;
1446 
1447   // Update the efficiency-since-mark vars.
1448   double proc_ms = elapsed_ms * (double) _parallel_gc_threads;
1449   if (elapsed_ms < MIN_TIMER_GRANULARITY) {
1450     // This usually happens due to the timer not having the required
1451     // granularity. Some Linuxes are the usual culprits.
1452     // We'll just set it to something (arbitrarily) small.
1453     proc_ms = 1.0;
1454   }
1455   double cur_efficiency = (double) freed_bytes / proc_ms;
1456 
1457   bool new_in_marking_window = _in_marking_window;
1458   bool new_in_marking_window_im = false;
1459   if (during_initial_mark_pause()) {
1460     new_in_marking_window = true;
1461     new_in_marking_window_im = true;
1462   }
1463 
1464   if (in_young_gc_mode()) {
1465     if (_last_full_young_gc) {
1466       set_full_young_gcs(false);
1467       _last_full_young_gc = false;
1468     }
1469 
1470     if ( !_last_young_gc_full ) {
1471       if ( _should_revert_to_full_young_gcs ||
1472            _known_garbage_ratio < 0.05 ||
1473            (adaptive_young_list_length() &&
1474            (get_gc_eff_factor() * cur_efficiency < predict_young_gc_eff())) ) {
1475         set_full_young_gcs(true);
1476       }
1477     }
1478     _should_revert_to_full_young_gcs = false;
1479 
1480     if (_last_young_gc_full && !_during_marking)
1481       _young_gc_eff_seq->add(cur_efficiency);
1482   }
1483 
1484   _short_lived_surv_rate_group->start_adding_regions();
1485   // do that for any other surv rate groupsx
1486 
1487   // <NEW PREDICTION>
1488 
1489   if (update_stats) {
1490     double pause_time_ms = elapsed_ms;
1491 
1492     size_t diff = 0;
1493     if (_max_pending_cards >= _pending_cards)
1494       diff = _max_pending_cards - _pending_cards;
1495     _pending_card_diff_seq->add((double) diff);
1496 
1497     double cost_per_card_ms = 0.0;
1498     if (_pending_cards > 0) {
1499       cost_per_card_ms = update_rs_time / (double) _pending_cards;
1500       _cost_per_card_ms_seq->add(cost_per_card_ms);
1501     }
1502 
1503     size_t cards_scanned = _g1->cards_scanned();
1504 
1505     double cost_per_entry_ms = 0.0;
1506     if (cards_scanned > 10) {
1507       cost_per_entry_ms = scan_rs_time / (double) cards_scanned;
1508       if (_last_young_gc_full)
1509         _cost_per_entry_ms_seq->add(cost_per_entry_ms);
1510       else
1511         _partially_young_cost_per_entry_ms_seq->add(cost_per_entry_ms);
1512     }
1513 
1514     if (_max_rs_lengths > 0) {
1515       double cards_per_entry_ratio =
1516         (double) cards_scanned / (double) _max_rs_lengths;
1517       if (_last_young_gc_full)
1518         _fully_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
1519       else
1520         _partially_young_cards_per_entry_ratio_seq->add(cards_per_entry_ratio);
1521     }
1522 
1523     size_t rs_length_diff = _max_rs_lengths - _recorded_rs_lengths;
1524     if (rs_length_diff >= 0)
1525       _rs_length_diff_seq->add((double) rs_length_diff);
1526 
1527     size_t copied_bytes = surviving_bytes;
1528     double cost_per_byte_ms = 0.0;
1529     if (copied_bytes > 0) {
1530       cost_per_byte_ms = obj_copy_time / (double) copied_bytes;
1531       if (_in_marking_window)
1532         _cost_per_byte_ms_during_cm_seq->add(cost_per_byte_ms);
1533       else
1534         _cost_per_byte_ms_seq->add(cost_per_byte_ms);
1535     }
1536 
1537     double all_other_time_ms = pause_time_ms -
1538       (update_rs_time + scan_rs_time + obj_copy_time +
1539        _mark_closure_time_ms + termination_time);
1540 
1541     double young_other_time_ms = 0.0;
1542     if (_recorded_young_regions > 0) {
1543       young_other_time_ms =
1544         _recorded_young_cset_choice_time_ms +
1545         _recorded_young_free_cset_time_ms;
1546       _young_other_cost_per_region_ms_seq->add(young_other_time_ms /
1547                                              (double) _recorded_young_regions);
1548     }
1549     double non_young_other_time_ms = 0.0;
1550     if (_recorded_non_young_regions > 0) {
1551       non_young_other_time_ms =
1552         _recorded_non_young_cset_choice_time_ms +
1553         _recorded_non_young_free_cset_time_ms;
1554 
1555       _non_young_other_cost_per_region_ms_seq->add(non_young_other_time_ms /
1556                                          (double) _recorded_non_young_regions);
1557     }
1558 
1559     double constant_other_time_ms = all_other_time_ms -
1560       (young_other_time_ms + non_young_other_time_ms);
1561     _constant_other_time_ms_seq->add(constant_other_time_ms);
1562 
1563     double survival_ratio = 0.0;
1564     if (_bytes_in_collection_set_before_gc > 0) {
1565       survival_ratio = (double) bytes_in_to_space_during_gc() /
1566         (double) _bytes_in_collection_set_before_gc;
1567     }
1568 
1569     _pending_cards_seq->add((double) _pending_cards);
1570     _scanned_cards_seq->add((double) cards_scanned);
1571     _rs_lengths_seq->add((double) _max_rs_lengths);
1572 
1573     double expensive_region_limit_ms =
1574       (double) MaxGCPauseMillis - predict_constant_other_time_ms();
1575     if (expensive_region_limit_ms < 0.0) {
1576       // this means that the other time was predicted to be longer than
1577       // than the max pause time
1578       expensive_region_limit_ms = (double) MaxGCPauseMillis;
1579     }
1580     _expensive_region_limit_ms = expensive_region_limit_ms;
1581 
1582     if (PREDICTIONS_VERBOSE) {
1583       gclog_or_tty->print_cr("");
1584       gclog_or_tty->print_cr("PREDICTIONS %1.4lf %d "
1585                     "REGIONS %d %d %d "
1586                     "PENDING_CARDS %d %d "
1587                     "CARDS_SCANNED %d %d "
1588                     "RS_LENGTHS %d %d "
1589                     "RS_UPDATE %1.6lf %1.6lf RS_SCAN %1.6lf %1.6lf "
1590                     "SURVIVAL_RATIO %1.6lf %1.6lf "
1591                     "OBJECT_COPY %1.6lf %1.6lf OTHER_CONSTANT %1.6lf %1.6lf "
1592                     "OTHER_YOUNG %1.6lf %1.6lf "
1593                     "OTHER_NON_YOUNG %1.6lf %1.6lf "
1594                     "VTIME_DIFF %1.6lf TERMINATION %1.6lf "
1595                     "ELAPSED %1.6lf %1.6lf ",
1596                     _cur_collection_start_sec,
1597                     (!_last_young_gc_full) ? 2 :
1598                     (last_pause_included_initial_mark) ? 1 : 0,
1599                     _recorded_region_num,
1600                     _recorded_young_regions,
1601                     _recorded_non_young_regions,
1602                     _predicted_pending_cards, _pending_cards,
1603                     _predicted_cards_scanned, cards_scanned,
1604                     _predicted_rs_lengths, _max_rs_lengths,
1605                     _predicted_rs_update_time_ms, update_rs_time,
1606                     _predicted_rs_scan_time_ms, scan_rs_time,
1607                     _predicted_survival_ratio, survival_ratio,
1608                     _predicted_object_copy_time_ms, obj_copy_time,
1609                     _predicted_constant_other_time_ms, constant_other_time_ms,
1610                     _predicted_young_other_time_ms, young_other_time_ms,
1611                     _predicted_non_young_other_time_ms,
1612                     non_young_other_time_ms,
1613                     _vtime_diff_ms, termination_time,
1614                     _predicted_pause_time_ms, elapsed_ms);
1615     }
1616 
1617     if (G1PolicyVerbose > 0) {
1618       gclog_or_tty->print_cr("Pause Time, predicted: %1.4lfms (predicted %s), actual: %1.4lfms",
1619                     _predicted_pause_time_ms,
1620                     (_within_target) ? "within" : "outside",
1621                     elapsed_ms);
1622     }
1623 
1624   }
1625 
1626   _in_marking_window = new_in_marking_window;
1627   _in_marking_window_im = new_in_marking_window_im;
1628   _free_regions_at_end_of_collection = _g1->free_regions();
1629   calculate_young_list_min_length();
1630   calculate_young_list_target_length();
1631 
1632   // Note that _mmu_tracker->max_gc_time() returns the time in seconds.
1633   double update_rs_time_goal_ms = _mmu_tracker->max_gc_time() * MILLIUNITS * G1RSetUpdatingPauseTimePercent / 100.0;
1634   adjust_concurrent_refinement(update_rs_time, update_rs_processed_buffers, update_rs_time_goal_ms);
1635   // </NEW PREDICTION>
1636 }
1637 
1638 // <NEW PREDICTION>
1639 
1640 void G1CollectorPolicy::adjust_concurrent_refinement(double update_rs_time,
1641                                                      double update_rs_processed_buffers,
1642                                                      double goal_ms) {
1643   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
1644   ConcurrentG1Refine *cg1r = G1CollectedHeap::heap()->concurrent_g1_refine();
1645 
1646   if (G1UseAdaptiveConcRefinement) {
1647     const int k_gy = 3, k_gr = 6;
1648     const double inc_k = 1.1, dec_k = 0.9;
1649 
1650     int g = cg1r->green_zone();
1651     if (update_rs_time > goal_ms) {
1652       g = (int)(g * dec_k);  // Can become 0, that's OK. That would mean a mutator-only processing.
1653     } else {
1654       if (update_rs_time < goal_ms && update_rs_processed_buffers > g) {
1655         g = (int)MAX2(g * inc_k, g + 1.0);
1656       }
1657     }
1658     // Change the refinement threads params
1659     cg1r->set_green_zone(g);
1660     cg1r->set_yellow_zone(g * k_gy);
1661     cg1r->set_red_zone(g * k_gr);
1662     cg1r->reinitialize_threads();
1663 
1664     int processing_threshold_delta = MAX2((int)(cg1r->green_zone() * sigma()), 1);
1665     int processing_threshold = MIN2(cg1r->green_zone() + processing_threshold_delta,
1666                                     cg1r->yellow_zone());
1667     // Change the barrier params
1668     dcqs.set_process_completed_threshold(processing_threshold);
1669     dcqs.set_max_completed_queue(cg1r->red_zone());
1670   }
1671 
1672   int curr_queue_size = dcqs.completed_buffers_num();
1673   if (curr_queue_size >= cg1r->yellow_zone()) {
1674     dcqs.set_completed_queue_padding(curr_queue_size);
1675   } else {
1676     dcqs.set_completed_queue_padding(0);
1677   }
1678   dcqs.notify_if_necessary();
1679 }
1680 
1681 double
1682 G1CollectorPolicy::
1683 predict_young_collection_elapsed_time_ms(size_t adjustment) {
1684   guarantee( adjustment == 0 || adjustment == 1, "invariant" );
1685 
1686   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1687   size_t young_num = g1h->young_list()->length();
1688   if (young_num == 0)
1689     return 0.0;
1690 
1691   young_num += adjustment;
1692   size_t pending_cards = predict_pending_cards();
1693   size_t rs_lengths = g1h->young_list()->sampled_rs_lengths() +
1694                       predict_rs_length_diff();
1695   size_t card_num;
1696   if (full_young_gcs())
1697     card_num = predict_young_card_num(rs_lengths);
1698   else
1699     card_num = predict_non_young_card_num(rs_lengths);
1700   size_t young_byte_size = young_num * HeapRegion::GrainBytes;
1701   double accum_yg_surv_rate =
1702     _short_lived_surv_rate_group->accum_surv_rate(adjustment);
1703 
1704   size_t bytes_to_copy =
1705     (size_t) (accum_yg_surv_rate * (double) HeapRegion::GrainBytes);
1706 
1707   return
1708     predict_rs_update_time_ms(pending_cards) +
1709     predict_rs_scan_time_ms(card_num) +
1710     predict_object_copy_time_ms(bytes_to_copy) +
1711     predict_young_other_time_ms(young_num) +
1712     predict_constant_other_time_ms();
1713 }
1714 
1715 double
1716 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) {
1717   size_t rs_length = predict_rs_length_diff();
1718   size_t card_num;
1719   if (full_young_gcs())
1720     card_num = predict_young_card_num(rs_length);
1721   else
1722     card_num = predict_non_young_card_num(rs_length);
1723   return predict_base_elapsed_time_ms(pending_cards, card_num);
1724 }
1725 
1726 double
1727 G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
1728                                                 size_t scanned_cards) {
1729   return
1730     predict_rs_update_time_ms(pending_cards) +
1731     predict_rs_scan_time_ms(scanned_cards) +
1732     predict_constant_other_time_ms();
1733 }
1734 
1735 double
1736 G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
1737                                                   bool young) {
1738   size_t rs_length = hr->rem_set()->occupied();
1739   size_t card_num;
1740   if (full_young_gcs())
1741     card_num = predict_young_card_num(rs_length);
1742   else
1743     card_num = predict_non_young_card_num(rs_length);
1744   size_t bytes_to_copy = predict_bytes_to_copy(hr);
1745 
1746   double region_elapsed_time_ms =
1747     predict_rs_scan_time_ms(card_num) +
1748     predict_object_copy_time_ms(bytes_to_copy);
1749 
1750   if (young)
1751     region_elapsed_time_ms += predict_young_other_time_ms(1);
1752   else
1753     region_elapsed_time_ms += predict_non_young_other_time_ms(1);
1754 
1755   return region_elapsed_time_ms;
1756 }
1757 
1758 size_t
1759 G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) {
1760   size_t bytes_to_copy;
1761   if (hr->is_marked())
1762     bytes_to_copy = hr->max_live_bytes();
1763   else {
1764     guarantee( hr->is_young() && hr->age_in_surv_rate_group() != -1,
1765                "invariant" );
1766     int age = hr->age_in_surv_rate_group();
1767     double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
1768     bytes_to_copy = (size_t) ((double) hr->used() * yg_surv_rate);
1769   }
1770 
1771   return bytes_to_copy;
1772 }
1773 
1774 void
1775 G1CollectorPolicy::start_recording_regions() {
1776   _recorded_rs_lengths            = 0;
1777   _recorded_young_regions         = 0;
1778   _recorded_non_young_regions     = 0;
1779 
1780 #if PREDICTIONS_VERBOSE
1781   _recorded_marked_bytes          = 0;
1782   _recorded_young_bytes           = 0;
1783   _predicted_bytes_to_copy        = 0;
1784   _predicted_rs_lengths           = 0;
1785   _predicted_cards_scanned        = 0;
1786 #endif // PREDICTIONS_VERBOSE
1787 }
1788 
1789 void
1790 G1CollectorPolicy::record_cset_region_info(HeapRegion* hr, bool young) {
1791 #if PREDICTIONS_VERBOSE
1792   if (!young) {
1793     _recorded_marked_bytes += hr->max_live_bytes();
1794   }
1795   _predicted_bytes_to_copy += predict_bytes_to_copy(hr);
1796 #endif // PREDICTIONS_VERBOSE
1797 
1798   size_t rs_length = hr->rem_set()->occupied();
1799   _recorded_rs_lengths += rs_length;
1800 }
1801 
1802 void
1803 G1CollectorPolicy::record_non_young_cset_region(HeapRegion* hr) {
1804   assert(!hr->is_young(), "should not call this");
1805   ++_recorded_non_young_regions;
1806   record_cset_region_info(hr, false);
1807 }
1808 
1809 void
1810 G1CollectorPolicy::set_recorded_young_regions(size_t n_regions) {
1811   _recorded_young_regions = n_regions;
1812 }
1813 
1814 void G1CollectorPolicy::set_recorded_young_bytes(size_t bytes) {
1815 #if PREDICTIONS_VERBOSE
1816   _recorded_young_bytes = bytes;
1817 #endif // PREDICTIONS_VERBOSE
1818 }
1819 
1820 void G1CollectorPolicy::set_recorded_rs_lengths(size_t rs_lengths) {
1821   _recorded_rs_lengths = rs_lengths;
1822 }
1823 
1824 void G1CollectorPolicy::set_predicted_bytes_to_copy(size_t bytes) {
1825   _predicted_bytes_to_copy = bytes;
1826 }
1827 
1828 void
1829 G1CollectorPolicy::end_recording_regions() {
1830   // The _predicted_pause_time_ms field is referenced in code
1831   // not under PREDICTIONS_VERBOSE. Let's initialize it.
1832   _predicted_pause_time_ms = -1.0;
1833 
1834 #if PREDICTIONS_VERBOSE
1835   _predicted_pending_cards = predict_pending_cards();
1836   _predicted_rs_lengths = _recorded_rs_lengths + predict_rs_length_diff();
1837   if (full_young_gcs())
1838     _predicted_cards_scanned += predict_young_card_num(_predicted_rs_lengths);
1839   else
1840     _predicted_cards_scanned +=
1841       predict_non_young_card_num(_predicted_rs_lengths);
1842   _recorded_region_num = _recorded_young_regions + _recorded_non_young_regions;
1843 
1844   _predicted_rs_update_time_ms =
1845     predict_rs_update_time_ms(_g1->pending_card_num());
1846   _predicted_rs_scan_time_ms =
1847     predict_rs_scan_time_ms(_predicted_cards_scanned);
1848   _predicted_object_copy_time_ms =
1849     predict_object_copy_time_ms(_predicted_bytes_to_copy);
1850   _predicted_constant_other_time_ms =
1851     predict_constant_other_time_ms();
1852   _predicted_young_other_time_ms =
1853     predict_young_other_time_ms(_recorded_young_regions);
1854   _predicted_non_young_other_time_ms =
1855     predict_non_young_other_time_ms(_recorded_non_young_regions);
1856 
1857   _predicted_pause_time_ms =
1858     _predicted_rs_update_time_ms +
1859     _predicted_rs_scan_time_ms +
1860     _predicted_object_copy_time_ms +
1861     _predicted_constant_other_time_ms +
1862     _predicted_young_other_time_ms +
1863     _predicted_non_young_other_time_ms;
1864 #endif // PREDICTIONS_VERBOSE
1865 }
1866 
1867 void G1CollectorPolicy::check_if_region_is_too_expensive(double
1868                                                            predicted_time_ms) {
1869   // I don't think we need to do this when in young GC mode since
1870   // marking will be initiated next time we hit the soft limit anyway...
1871   if (predicted_time_ms > _expensive_region_limit_ms) {
1872     if (!in_young_gc_mode()) {
1873         set_full_young_gcs(true);
1874         // We might want to do something different here. However,
1875         // right now we don't support the non-generational G1 mode
1876         // (and in fact we are planning to remove the associated code,
1877         // see CR 6814390). So, let's leave it as is and this will be
1878         // removed some time in the future
1879         ShouldNotReachHere();
1880         set_during_initial_mark_pause();
1881     } else
1882       // no point in doing another partial one
1883       _should_revert_to_full_young_gcs = true;
1884   }
1885 }
1886 
1887 // </NEW PREDICTION>
1888 
1889 
1890 void G1CollectorPolicy::update_recent_gc_times(double end_time_sec,
1891                                                double elapsed_ms) {
1892   _recent_gc_times_ms->add(elapsed_ms);
1893   _recent_prev_end_times_for_all_gcs_sec->add(end_time_sec);
1894   _prev_collection_pause_end_ms = end_time_sec * 1000.0;
1895 }
1896 
1897 double G1CollectorPolicy::recent_avg_time_for_pauses_ms() {
1898   if (_recent_pause_times_ms->num() == 0) return (double) MaxGCPauseMillis;
1899   else return _recent_pause_times_ms->avg();
1900 }
1901 
1902 double G1CollectorPolicy::recent_avg_time_for_CH_strong_ms() {
1903   if (_recent_CH_strong_roots_times_ms->num() == 0)
1904     return (double)MaxGCPauseMillis/3.0;
1905   else return _recent_CH_strong_roots_times_ms->avg();
1906 }
1907 
1908 double G1CollectorPolicy::recent_avg_time_for_G1_strong_ms() {
1909   if (_recent_G1_strong_roots_times_ms->num() == 0)
1910     return (double)MaxGCPauseMillis/3.0;
1911   else return _recent_G1_strong_roots_times_ms->avg();
1912 }
1913 
1914 double G1CollectorPolicy::recent_avg_time_for_evac_ms() {
1915   if (_recent_evac_times_ms->num() == 0) return (double)MaxGCPauseMillis/3.0;
1916   else return _recent_evac_times_ms->avg();
1917 }
1918 
1919 int G1CollectorPolicy::number_of_recent_gcs() {
1920   assert(_recent_CH_strong_roots_times_ms->num() ==
1921          _recent_G1_strong_roots_times_ms->num(), "Sequence out of sync");
1922   assert(_recent_G1_strong_roots_times_ms->num() ==
1923          _recent_evac_times_ms->num(), "Sequence out of sync");
1924   assert(_recent_evac_times_ms->num() ==
1925          _recent_pause_times_ms->num(), "Sequence out of sync");
1926   assert(_recent_pause_times_ms->num() ==
1927          _recent_CS_bytes_used_before->num(), "Sequence out of sync");
1928   assert(_recent_CS_bytes_used_before->num() ==
1929          _recent_CS_bytes_surviving->num(), "Sequence out of sync");
1930   return _recent_pause_times_ms->num();
1931 }
1932 
1933 double G1CollectorPolicy::recent_avg_survival_fraction() {
1934   return recent_avg_survival_fraction_work(_recent_CS_bytes_surviving,
1935                                            _recent_CS_bytes_used_before);
1936 }
1937 
1938 double G1CollectorPolicy::last_survival_fraction() {
1939   return last_survival_fraction_work(_recent_CS_bytes_surviving,
1940                                      _recent_CS_bytes_used_before);
1941 }
1942 
1943 double
1944 G1CollectorPolicy::recent_avg_survival_fraction_work(TruncatedSeq* surviving,
1945                                                      TruncatedSeq* before) {
1946   assert(surviving->num() == before->num(), "Sequence out of sync");
1947   if (before->sum() > 0.0) {
1948       double recent_survival_rate = surviving->sum() / before->sum();
1949       // We exempt parallel collection from this check because Alloc Buffer
1950       // fragmentation can produce negative collections.
1951       // Further, we're now always doing parallel collection.  But I'm still
1952       // leaving this here as a placeholder for a more precise assertion later.
1953       // (DLD, 10/05.)
1954       assert((true || ParallelGCThreads > 0) ||
1955              _g1->evacuation_failed() ||
1956              recent_survival_rate <= 1.0, "Or bad frac");
1957       return recent_survival_rate;
1958   } else {
1959     return 1.0; // Be conservative.
1960   }
1961 }
1962 
1963 double
1964 G1CollectorPolicy::last_survival_fraction_work(TruncatedSeq* surviving,
1965                                                TruncatedSeq* before) {
1966   assert(surviving->num() == before->num(), "Sequence out of sync");
1967   if (surviving->num() > 0 && before->last() > 0.0) {
1968     double last_survival_rate = surviving->last() / before->last();
1969     // We exempt parallel collection from this check because Alloc Buffer
1970     // fragmentation can produce negative collections.
1971     // Further, we're now always doing parallel collection.  But I'm still
1972     // leaving this here as a placeholder for a more precise assertion later.
1973     // (DLD, 10/05.)
1974     assert((true || ParallelGCThreads > 0) ||
1975            last_survival_rate <= 1.0, "Or bad frac");
1976     return last_survival_rate;
1977   } else {
1978     return 1.0;
1979   }
1980 }
1981 
1982 static const int survival_min_obs = 5;
1983 static double survival_min_obs_limits[] = { 0.9, 0.7, 0.5, 0.3, 0.1 };
1984 static const double min_survival_rate = 0.1;
1985 
1986 double
1987 G1CollectorPolicy::conservative_avg_survival_fraction_work(double avg,
1988                                                            double latest) {
1989   double res = avg;
1990   if (number_of_recent_gcs() < survival_min_obs) {
1991     res = MAX2(res, survival_min_obs_limits[number_of_recent_gcs()]);
1992   }
1993   res = MAX2(res, latest);
1994   res = MAX2(res, min_survival_rate);
1995   // In the parallel case, LAB fragmentation can produce "negative
1996   // collections"; so can evac failure.  Cap at 1.0
1997   res = MIN2(res, 1.0);
1998   return res;
1999 }
2000 
2001 size_t G1CollectorPolicy::expansion_amount() {
2002   if ((recent_avg_pause_time_ratio() * 100.0) > _gc_overhead_perc) {
2003     // We will double the existing space, or take
2004     // G1ExpandByPercentOfAvailable % of the available expansion
2005     // space, whichever is smaller, bounded below by a minimum
2006     // expansion (unless that's all that's left.)
2007     const size_t min_expand_bytes = 1*M;
2008     size_t reserved_bytes = _g1->g1_reserved_obj_bytes();
2009     size_t committed_bytes = _g1->capacity();
2010     size_t uncommitted_bytes = reserved_bytes - committed_bytes;
2011     size_t expand_bytes;
2012     size_t expand_bytes_via_pct =
2013       uncommitted_bytes * G1ExpandByPercentOfAvailable / 100;
2014     expand_bytes = MIN2(expand_bytes_via_pct, committed_bytes);
2015     expand_bytes = MAX2(expand_bytes, min_expand_bytes);
2016     expand_bytes = MIN2(expand_bytes, uncommitted_bytes);
2017     if (G1PolicyVerbose > 1) {
2018       gclog_or_tty->print("Decided to expand: ratio = %5.2f, "
2019                  "committed = %d%s, uncommited = %d%s, via pct = %d%s.\n"
2020                  "                   Answer = %d.\n",
2021                  recent_avg_pause_time_ratio(),
2022                  byte_size_in_proper_unit(committed_bytes),
2023                  proper_unit_for_byte_size(committed_bytes),
2024                  byte_size_in_proper_unit(uncommitted_bytes),
2025                  proper_unit_for_byte_size(uncommitted_bytes),
2026                  byte_size_in_proper_unit(expand_bytes_via_pct),
2027                  proper_unit_for_byte_size(expand_bytes_via_pct),
2028                  byte_size_in_proper_unit(expand_bytes),
2029                  proper_unit_for_byte_size(expand_bytes));
2030     }
2031     return expand_bytes;
2032   } else {
2033     return 0;
2034   }
2035 }
2036 
2037 void G1CollectorPolicy::note_start_of_mark_thread() {
2038   _mark_thread_startup_sec = os::elapsedTime();
2039 }
2040 
2041 class CountCSClosure: public HeapRegionClosure {
2042   G1CollectorPolicy* _g1_policy;
2043 public:
2044   CountCSClosure(G1CollectorPolicy* g1_policy) :
2045     _g1_policy(g1_policy) {}
2046   bool doHeapRegion(HeapRegion* r) {
2047     _g1_policy->_bytes_in_collection_set_before_gc += r->used();
2048     return false;
2049   }
2050 };
2051 
2052 void G1CollectorPolicy::count_CS_bytes_used() {
2053   CountCSClosure cs_closure(this);
2054   _g1->collection_set_iterate(&cs_closure);
2055 }
2056 
2057 static void print_indent(int level) {
2058   for (int j = 0; j < level+1; ++j)
2059     gclog_or_tty->print("   ");
2060 }
2061 
2062 void G1CollectorPolicy::print_summary (int level,
2063                                        const char* str,
2064                                        NumberSeq* seq) const {
2065   double sum = seq->sum();
2066   print_indent(level);
2067   gclog_or_tty->print_cr("%-24s = %8.2lf s (avg = %8.2lf ms)",
2068                 str, sum / 1000.0, seq->avg());
2069 }
2070 
2071 void G1CollectorPolicy::print_summary_sd (int level,
2072                                           const char* str,
2073                                           NumberSeq* seq) const {
2074   print_summary(level, str, seq);
2075   print_indent(level + 5);
2076   gclog_or_tty->print_cr("(num = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
2077                 seq->num(), seq->sd(), seq->maximum());
2078 }
2079 
2080 void G1CollectorPolicy::check_other_times(int level,
2081                                         NumberSeq* other_times_ms,
2082                                         NumberSeq* calc_other_times_ms) const {
2083   bool should_print = false;
2084 
2085   double max_sum = MAX2(fabs(other_times_ms->sum()),
2086                         fabs(calc_other_times_ms->sum()));
2087   double min_sum = MIN2(fabs(other_times_ms->sum()),
2088                         fabs(calc_other_times_ms->sum()));
2089   double sum_ratio = max_sum / min_sum;
2090   if (sum_ratio > 1.1) {
2091     should_print = true;
2092     print_indent(level + 1);
2093     gclog_or_tty->print_cr("## CALCULATED OTHER SUM DOESN'T MATCH RECORDED ###");
2094   }
2095 
2096   double max_avg = MAX2(fabs(other_times_ms->avg()),
2097                         fabs(calc_other_times_ms->avg()));
2098   double min_avg = MIN2(fabs(other_times_ms->avg()),
2099                         fabs(calc_other_times_ms->avg()));
2100   double avg_ratio = max_avg / min_avg;
2101   if (avg_ratio > 1.1) {
2102     should_print = true;
2103     print_indent(level + 1);
2104     gclog_or_tty->print_cr("## CALCULATED OTHER AVG DOESN'T MATCH RECORDED ###");
2105   }
2106 
2107   if (other_times_ms->sum() < -0.01) {
2108     print_indent(level + 1);
2109     gclog_or_tty->print_cr("## RECORDED OTHER SUM IS NEGATIVE ###");
2110   }
2111 
2112   if (other_times_ms->avg() < -0.01) {
2113     print_indent(level + 1);
2114     gclog_or_tty->print_cr("## RECORDED OTHER AVG IS NEGATIVE ###");
2115   }
2116 
2117   if (calc_other_times_ms->sum() < -0.01) {
2118     should_print = true;
2119     print_indent(level + 1);
2120     gclog_or_tty->print_cr("## CALCULATED OTHER SUM IS NEGATIVE ###");
2121   }
2122 
2123   if (calc_other_times_ms->avg() < -0.01) {
2124     should_print = true;
2125     print_indent(level + 1);
2126     gclog_or_tty->print_cr("## CALCULATED OTHER AVG IS NEGATIVE ###");
2127   }
2128 
2129   if (should_print)
2130     print_summary(level, "Other(Calc)", calc_other_times_ms);
2131 }
2132 
2133 void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
2134   bool parallel = ParallelGCThreads > 0;
2135   MainBodySummary*    body_summary = summary->main_body_summary();
2136   if (summary->get_total_seq()->num() > 0) {
2137     print_summary_sd(0, "Evacuation Pauses", summary->get_total_seq());
2138     if (body_summary != NULL) {
2139       print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
2140       if (parallel) {
2141         print_summary(1, "Parallel Time", body_summary->get_parallel_seq());
2142         print_summary(2, "Update RS", body_summary->get_update_rs_seq());
2143         print_summary(2, "Ext Root Scanning",
2144                       body_summary->get_ext_root_scan_seq());
2145         print_summary(2, "Mark Stack Scanning",
2146                       body_summary->get_mark_stack_scan_seq());
2147         print_summary(2, "Scan RS", body_summary->get_scan_rs_seq());
2148         print_summary(2, "Object Copy", body_summary->get_obj_copy_seq());
2149         print_summary(2, "Termination", body_summary->get_termination_seq());
2150         print_summary(2, "Other", body_summary->get_parallel_other_seq());
2151         {
2152           NumberSeq* other_parts[] = {
2153             body_summary->get_update_rs_seq(),
2154             body_summary->get_ext_root_scan_seq(),
2155             body_summary->get_mark_stack_scan_seq(),
2156             body_summary->get_scan_rs_seq(),
2157             body_summary->get_obj_copy_seq(),
2158             body_summary->get_termination_seq()
2159           };
2160           NumberSeq calc_other_times_ms(body_summary->get_parallel_seq(),
2161                                         6, other_parts);
2162           check_other_times(2, body_summary->get_parallel_other_seq(),
2163                             &calc_other_times_ms);
2164         }
2165         print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
2166         print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
2167       } else {
2168         print_summary(1, "Update RS", body_summary->get_update_rs_seq());
2169         print_summary(1, "Ext Root Scanning",
2170                       body_summary->get_ext_root_scan_seq());
2171         print_summary(1, "Mark Stack Scanning",
2172                       body_summary->get_mark_stack_scan_seq());
2173         print_summary(1, "Scan RS", body_summary->get_scan_rs_seq());
2174         print_summary(1, "Object Copy", body_summary->get_obj_copy_seq());
2175       }
2176     }
2177     print_summary(1, "Other", summary->get_other_seq());
2178     {
2179       if (body_summary != NULL) {
2180         NumberSeq calc_other_times_ms;
2181         if (parallel) {
2182           // parallel
2183           NumberSeq* other_parts[] = {
2184             body_summary->get_satb_drain_seq(),
2185             body_summary->get_parallel_seq(),
2186             body_summary->get_clear_ct_seq()
2187           };
2188           calc_other_times_ms = NumberSeq(summary->get_total_seq(),
2189                                                 3, other_parts);
2190         } else {
2191           // serial
2192           NumberSeq* other_parts[] = {
2193             body_summary->get_satb_drain_seq(),
2194             body_summary->get_update_rs_seq(),
2195             body_summary->get_ext_root_scan_seq(),
2196             body_summary->get_mark_stack_scan_seq(),
2197             body_summary->get_scan_rs_seq(),
2198             body_summary->get_obj_copy_seq()
2199           };
2200           calc_other_times_ms = NumberSeq(summary->get_total_seq(),
2201                                                 6, other_parts);
2202         }
2203         check_other_times(1,  summary->get_other_seq(), &calc_other_times_ms);
2204       }
2205     }
2206   } else {
2207     print_indent(0);
2208     gclog_or_tty->print_cr("none");
2209   }
2210   gclog_or_tty->print_cr("");
2211 }
2212 
2213 void G1CollectorPolicy::print_tracing_info() const {
2214   if (TraceGen0Time) {
2215     gclog_or_tty->print_cr("ALL PAUSES");
2216     print_summary_sd(0, "Total", _all_pause_times_ms);
2217     gclog_or_tty->print_cr("");
2218     gclog_or_tty->print_cr("");
2219     gclog_or_tty->print_cr("   Full Young GC Pauses:    %8d", _full_young_pause_num);
2220     gclog_or_tty->print_cr("   Partial Young GC Pauses: %8d", _partial_young_pause_num);
2221     gclog_or_tty->print_cr("");
2222 
2223     gclog_or_tty->print_cr("EVACUATION PAUSES");
2224     print_summary(_summary);
2225 
2226     gclog_or_tty->print_cr("MISC");
2227     print_summary_sd(0, "Stop World", _all_stop_world_times_ms);
2228     print_summary_sd(0, "Yields", _all_yield_times_ms);
2229     for (int i = 0; i < _aux_num; ++i) {
2230       if (_all_aux_times_ms[i].num() > 0) {
2231         char buffer[96];
2232         sprintf(buffer, "Aux%d", i);
2233         print_summary_sd(0, buffer, &_all_aux_times_ms[i]);
2234       }
2235     }
2236 
2237     size_t all_region_num = _region_num_young + _region_num_tenured;
2238     gclog_or_tty->print_cr("   New Regions %8d, Young %8d (%6.2lf%%), "
2239                "Tenured %8d (%6.2lf%%)",
2240                all_region_num,
2241                _region_num_young,
2242                (double) _region_num_young / (double) all_region_num * 100.0,
2243                _region_num_tenured,
2244                (double) _region_num_tenured / (double) all_region_num * 100.0);
2245   }
2246   if (TraceGen1Time) {
2247     if (_all_full_gc_times_ms->num() > 0) {
2248       gclog_or_tty->print("\n%4d full_gcs: total time = %8.2f s",
2249                  _all_full_gc_times_ms->num(),
2250                  _all_full_gc_times_ms->sum() / 1000.0);
2251       gclog_or_tty->print_cr(" (avg = %8.2fms).", _all_full_gc_times_ms->avg());
2252       gclog_or_tty->print_cr("                     [std. dev = %8.2f ms, max = %8.2f ms]",
2253                     _all_full_gc_times_ms->sd(),
2254                     _all_full_gc_times_ms->maximum());
2255     }
2256   }
2257 }
2258 
2259 void G1CollectorPolicy::print_yg_surv_rate_info() const {
2260 #ifndef PRODUCT
2261   _short_lived_surv_rate_group->print_surv_rate_summary();
2262   // add this call for any other surv rate groups
2263 #endif // PRODUCT
2264 }
2265 
2266 bool
2267 G1CollectorPolicy::should_add_next_region_to_young_list() {
2268   assert(in_young_gc_mode(), "should be in young GC mode");
2269   bool ret;
2270   size_t young_list_length = _g1->young_list()->length();
2271   size_t young_list_max_length = _young_list_target_length;
2272   if (G1FixedEdenSize) {
2273     young_list_max_length -= _max_survivor_regions;
2274   }
2275   if (young_list_length < young_list_max_length) {
2276     ret = true;
2277     ++_region_num_young;
2278   } else {
2279     ret = false;
2280     ++_region_num_tenured;
2281   }
2282 
2283   return ret;
2284 }
2285 
2286 #ifndef PRODUCT
2287 // for debugging, bit of a hack...
2288 static char*
2289 region_num_to_mbs(int length) {
2290   static char buffer[64];
2291   double bytes = (double) (length * HeapRegion::GrainBytes);
2292   double mbs = bytes / (double) (1024 * 1024);
2293   sprintf(buffer, "%7.2lfMB", mbs);
2294   return buffer;
2295 }
2296 #endif // PRODUCT
2297 
2298 size_t G1CollectorPolicy::max_regions(int purpose) {
2299   switch (purpose) {
2300     case GCAllocForSurvived:
2301       return _max_survivor_regions;
2302     case GCAllocForTenured:
2303       return REGIONS_UNLIMITED;
2304     default:
2305       ShouldNotReachHere();
2306       return REGIONS_UNLIMITED;
2307   };
2308 }
2309 
2310 // Calculates survivor space parameters.
2311 void G1CollectorPolicy::calculate_survivors_policy()
2312 {
2313   if (G1FixedSurvivorSpaceSize == 0) {
2314     _max_survivor_regions = _young_list_target_length / SurvivorRatio;
2315   } else {
2316     _max_survivor_regions = G1FixedSurvivorSpaceSize / HeapRegion::GrainBytes;
2317   }
2318 
2319   if (G1FixedTenuringThreshold) {
2320     _tenuring_threshold = MaxTenuringThreshold;
2321   } else {
2322     _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
2323         HeapRegion::GrainWords * _max_survivor_regions);
2324   }
2325 }
2326 
2327 bool
2328 G1CollectorPolicy_BestRegionsFirst::should_do_collection_pause(size_t
2329                                                                word_size) {
2330   assert(_g1->regions_accounted_for(), "Region leakage!");
2331   double max_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
2332 
2333   size_t young_list_length = _g1->young_list()->length();
2334   size_t young_list_max_length = _young_list_target_length;
2335   if (G1FixedEdenSize) {
2336     young_list_max_length -= _max_survivor_regions;
2337   }
2338   bool reached_target_length = young_list_length >= young_list_max_length;
2339 
2340   if (in_young_gc_mode()) {
2341     if (reached_target_length) {
2342       assert( young_list_length > 0 && _g1->young_list()->length() > 0,
2343               "invariant" );
2344       return true;
2345     }
2346   } else {
2347     guarantee( false, "should not reach here" );
2348   }
2349 
2350   return false;
2351 }
2352 
2353 #ifndef PRODUCT
2354 class HRSortIndexIsOKClosure: public HeapRegionClosure {
2355   CollectionSetChooser* _chooser;
2356 public:
2357   HRSortIndexIsOKClosure(CollectionSetChooser* chooser) :
2358     _chooser(chooser) {}
2359 
2360   bool doHeapRegion(HeapRegion* r) {
2361     if (!r->continuesHumongous()) {
2362       assert(_chooser->regionProperlyOrdered(r), "Ought to be.");
2363     }
2364     return false;
2365   }
2366 };
2367 
2368 bool G1CollectorPolicy_BestRegionsFirst::assertMarkedBytesDataOK() {
2369   HRSortIndexIsOKClosure cl(_collectionSetChooser);
2370   _g1->heap_region_iterate(&cl);
2371   return true;
2372 }
2373 #endif
2374 
2375 bool
2376 G1CollectorPolicy::force_initial_mark_if_outside_cycle() {
2377   bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();
2378   if (!during_cycle) {
2379     set_initiate_conc_mark_if_possible();
2380     return true;
2381   } else {
2382     return false;
2383   }
2384 }
2385 
2386 void
2387 G1CollectorPolicy::decide_on_conc_mark_initiation() {
2388   // We are about to decide on whether this pause will be an
2389   // initial-mark pause.
2390 
2391   // First, during_initial_mark_pause() should not be already set. We
2392   // will set it here if we have to. However, it should be cleared by
2393   // the end of the pause (it's only set for the duration of an
2394   // initial-mark pause).
2395   assert(!during_initial_mark_pause(), "pre-condition");
2396 
2397   if (initiate_conc_mark_if_possible()) {
2398     // We had noticed on a previous pause that the heap occupancy has
2399     // gone over the initiating threshold and we should start a
2400     // concurrent marking cycle. So we might initiate one.
2401 
2402     bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();
2403     if (!during_cycle) {
2404       // The concurrent marking thread is not "during a cycle", i.e.,
2405       // it has completed the last one. So we can go ahead and
2406       // initiate a new cycle.
2407 
2408       set_during_initial_mark_pause();
2409 
2410       // And we can now clear initiate_conc_mark_if_possible() as
2411       // we've already acted on it.
2412       clear_initiate_conc_mark_if_possible();
2413     } else {
2414       // The concurrent marking thread is still finishing up the
2415       // previous cycle. If we start one right now the two cycles
2416       // overlap. In particular, the concurrent marking thread might
2417       // be in the process of clearing the next marking bitmap (which
2418       // we will use for the next cycle if we start one). Starting a
2419       // cycle now will be bad given that parts of the marking
2420       // information might get cleared by the marking thread. And we
2421       // cannot wait for the marking thread to finish the cycle as it
2422       // periodically yields while clearing the next marking bitmap
2423       // and, if it's in a yield point, it's waiting for us to
2424       // finish. So, at this point we will not start a cycle and we'll
2425       // let the concurrent marking thread complete the last one.
2426     }
2427   }
2428 }
2429 
2430 void
2431 G1CollectorPolicy_BestRegionsFirst::
2432 record_collection_pause_start(double start_time_sec, size_t start_used) {
2433   G1CollectorPolicy::record_collection_pause_start(start_time_sec, start_used);
2434 }
2435 
2436 class NextNonCSElemFinder: public HeapRegionClosure {
2437   HeapRegion* _res;
2438 public:
2439   NextNonCSElemFinder(): _res(NULL) {}
2440   bool doHeapRegion(HeapRegion* r) {
2441     if (!r->in_collection_set()) {
2442       _res = r;
2443       return true;
2444     } else {
2445       return false;
2446     }
2447   }
2448   HeapRegion* res() { return _res; }
2449 };
2450 
2451 class KnownGarbageClosure: public HeapRegionClosure {
2452   CollectionSetChooser* _hrSorted;
2453 
2454 public:
2455   KnownGarbageClosure(CollectionSetChooser* hrSorted) :
2456     _hrSorted(hrSorted)
2457   {}
2458 
2459   bool doHeapRegion(HeapRegion* r) {
2460     // We only include humongous regions in collection
2461     // sets when concurrent mark shows that their contained object is
2462     // unreachable.
2463 
2464     // Do we have any marking information for this region?
2465     if (r->is_marked()) {
2466       // We don't include humongous regions in collection
2467       // sets because we collect them immediately at the end of a marking
2468       // cycle.  We also don't include young regions because we *must*
2469       // include them in the next collection pause.
2470       if (!r->isHumongous() && !r->is_young()) {
2471         _hrSorted->addMarkedHeapRegion(r);
2472       }
2473     }
2474     return false;
2475   }
2476 };
2477 
2478 class ParKnownGarbageHRClosure: public HeapRegionClosure {
2479   CollectionSetChooser* _hrSorted;
2480   jint _marked_regions_added;
2481   jint _chunk_size;
2482   jint _cur_chunk_idx;
2483   jint _cur_chunk_end; // Cur chunk [_cur_chunk_idx, _cur_chunk_end)
2484   int _worker;
2485   int _invokes;
2486 
2487   void get_new_chunk() {
2488     _cur_chunk_idx = _hrSorted->getParMarkedHeapRegionChunk(_chunk_size);
2489     _cur_chunk_end = _cur_chunk_idx + _chunk_size;
2490   }
2491   void add_region(HeapRegion* r) {
2492     if (_cur_chunk_idx == _cur_chunk_end) {
2493       get_new_chunk();
2494     }
2495     assert(_cur_chunk_idx < _cur_chunk_end, "postcondition");
2496     _hrSorted->setMarkedHeapRegion(_cur_chunk_idx, r);
2497     _marked_regions_added++;
2498     _cur_chunk_idx++;
2499   }
2500 
2501 public:
2502   ParKnownGarbageHRClosure(CollectionSetChooser* hrSorted,
2503                            jint chunk_size,
2504                            int worker) :
2505     _hrSorted(hrSorted), _chunk_size(chunk_size), _worker(worker),
2506     _marked_regions_added(0), _cur_chunk_idx(0), _cur_chunk_end(0),
2507     _invokes(0)
2508   {}
2509 
2510   bool doHeapRegion(HeapRegion* r) {
2511     // We only include humongous regions in collection
2512     // sets when concurrent mark shows that their contained object is
2513     // unreachable.
2514     _invokes++;
2515 
2516     // Do we have any marking information for this region?
2517     if (r->is_marked()) {
2518       // We don't include humongous regions in collection
2519       // sets because we collect them immediately at the end of a marking
2520       // cycle.
2521       // We also do not include young regions in collection sets
2522       if (!r->isHumongous() && !r->is_young()) {
2523         add_region(r);
2524       }
2525     }
2526     return false;
2527   }
2528   jint marked_regions_added() { return _marked_regions_added; }
2529   int invokes() { return _invokes; }
2530 };
2531 
2532 class ParKnownGarbageTask: public AbstractGangTask {
2533   CollectionSetChooser* _hrSorted;
2534   jint _chunk_size;
2535   G1CollectedHeap* _g1;
2536 public:
2537   ParKnownGarbageTask(CollectionSetChooser* hrSorted, jint chunk_size) :
2538     AbstractGangTask("ParKnownGarbageTask"),
2539     _hrSorted(hrSorted), _chunk_size(chunk_size),
2540     _g1(G1CollectedHeap::heap())
2541   {}
2542 
2543   void work(int i) {
2544     ParKnownGarbageHRClosure parKnownGarbageCl(_hrSorted, _chunk_size, i);
2545     // Back to zero for the claim value.
2546     _g1->heap_region_par_iterate_chunked(&parKnownGarbageCl, i,
2547                                          HeapRegion::InitialClaimValue);
2548     jint regions_added = parKnownGarbageCl.marked_regions_added();
2549     _hrSorted->incNumMarkedHeapRegions(regions_added);
2550     if (G1PrintParCleanupStats) {
2551       gclog_or_tty->print("     Thread %d called %d times, added %d regions to list.\n",
2552                  i, parKnownGarbageCl.invokes(), regions_added);
2553     }
2554   }
2555 };
2556 
2557 void
2558 G1CollectorPolicy_BestRegionsFirst::
2559 record_concurrent_mark_cleanup_end(size_t freed_bytes,
2560                                    size_t max_live_bytes) {
2561   double start;
2562   if (G1PrintParCleanupStats) start = os::elapsedTime();
2563   record_concurrent_mark_cleanup_end_work1(freed_bytes, max_live_bytes);
2564 
2565   _collectionSetChooser->clearMarkedHeapRegions();
2566   double clear_marked_end;
2567   if (G1PrintParCleanupStats) {
2568     clear_marked_end = os::elapsedTime();
2569     gclog_or_tty->print_cr("  clear marked regions + work1: %8.3f ms.",
2570                   (clear_marked_end - start)*1000.0);
2571   }
2572   if (ParallelGCThreads > 0) {
2573     const size_t OverpartitionFactor = 4;
2574     const size_t MinWorkUnit = 8;
2575     const size_t WorkUnit =
2576       MAX2(_g1->n_regions() / (ParallelGCThreads * OverpartitionFactor),
2577            MinWorkUnit);
2578     _collectionSetChooser->prepareForAddMarkedHeapRegionsPar(_g1->n_regions(),
2579                                                              WorkUnit);
2580     ParKnownGarbageTask parKnownGarbageTask(_collectionSetChooser,
2581                                             (int) WorkUnit);
2582     _g1->workers()->run_task(&parKnownGarbageTask);
2583 
2584     assert(_g1->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2585            "sanity check");
2586   } else {
2587     KnownGarbageClosure knownGarbagecl(_collectionSetChooser);
2588     _g1->heap_region_iterate(&knownGarbagecl);
2589   }
2590   double known_garbage_end;
2591   if (G1PrintParCleanupStats) {
2592     known_garbage_end = os::elapsedTime();
2593     gclog_or_tty->print_cr("  compute known garbage: %8.3f ms.",
2594                   (known_garbage_end - clear_marked_end)*1000.0);
2595   }
2596   _collectionSetChooser->sortMarkedHeapRegions();
2597   double sort_end;
2598   if (G1PrintParCleanupStats) {
2599     sort_end = os::elapsedTime();
2600     gclog_or_tty->print_cr("  sorting: %8.3f ms.",
2601                   (sort_end - known_garbage_end)*1000.0);
2602   }
2603 
2604   record_concurrent_mark_cleanup_end_work2();
2605   double work2_end;
2606   if (G1PrintParCleanupStats) {
2607     work2_end = os::elapsedTime();
2608     gclog_or_tty->print_cr("  work2: %8.3f ms.",
2609                   (work2_end - sort_end)*1000.0);
2610   }
2611 }
2612 
2613 // Add the heap region at the head of the non-incremental collection set
2614 void G1CollectorPolicy::
2615 add_to_collection_set(HeapRegion* hr) {
2616   assert(_inc_cset_build_state == Active, "Precondition");
2617   assert(!hr->is_young(), "non-incremental add of young region");
2618 
2619   if (G1PrintHeapRegions) {
2620     gclog_or_tty->print_cr("added region to cset "
2621                            "%d:["PTR_FORMAT", "PTR_FORMAT"], "
2622                            "top "PTR_FORMAT", %s",
2623                            hr->hrs_index(), hr->bottom(), hr->end(),
2624                            hr->top(), hr->is_young() ? "YOUNG" : "NOT_YOUNG");
2625   }
2626 
2627   if (_g1->mark_in_progress())
2628     _g1->concurrent_mark()->registerCSetRegion(hr);
2629 
2630   assert(!hr->in_collection_set(), "should not already be in the CSet");
2631   hr->set_in_collection_set(true);
2632   hr->set_next_in_collection_set(_collection_set);
2633   _collection_set = hr;
2634   _collection_set_size++;
2635   _collection_set_bytes_used_before += hr->used();
2636   _g1->register_region_with_in_cset_fast_test(hr);
2637 }
2638 
2639 // Initialize the per-collection-set information
2640 void G1CollectorPolicy::start_incremental_cset_building() {
2641   assert(_inc_cset_build_state == Inactive, "Precondition");
2642 
2643   _inc_cset_head = NULL;
2644   _inc_cset_tail = NULL;
2645   _inc_cset_size = 0;
2646   _inc_cset_bytes_used_before = 0;
2647 
2648   if (in_young_gc_mode()) {
2649     _inc_cset_young_index = 0;
2650   }
2651 
2652   _inc_cset_max_finger = 0;
2653   _inc_cset_recorded_young_bytes = 0;
2654   _inc_cset_recorded_rs_lengths = 0;
2655   _inc_cset_predicted_elapsed_time_ms = 0;
2656   _inc_cset_predicted_bytes_to_copy = 0;
2657   _inc_cset_build_state = Active;
2658 }
2659 
2660 void G1CollectorPolicy::add_to_incremental_cset_info(HeapRegion* hr, size_t rs_length) {
2661   // This routine is used when:
2662   // * adding survivor regions to the incremental cset at the end of an
2663   //   evacuation pause,
2664   // * adding the current allocation region to the incremental cset
2665   //   when it is retired, and
2666   // * updating existing policy information for a region in the
2667   //   incremental cset via young list RSet sampling.
2668   // Therefore this routine may be called at a safepoint by the
2669   // VM thread, or in-between safepoints by mutator threads (when
2670   // retiring the current allocation region) or a concurrent
2671   // refine thread (RSet sampling).
2672 
2673   double region_elapsed_time_ms = predict_region_elapsed_time_ms(hr, true);
2674   size_t used_bytes = hr->used();
2675 
2676   _inc_cset_recorded_rs_lengths += rs_length;
2677   _inc_cset_predicted_elapsed_time_ms += region_elapsed_time_ms;
2678 
2679   _inc_cset_bytes_used_before += used_bytes;
2680 
2681   // Cache the values we have added to the aggregated informtion
2682   // in the heap region in case we have to remove this region from
2683   // the incremental collection set, or it is updated by the
2684   // rset sampling code
2685   hr->set_recorded_rs_length(rs_length);
2686   hr->set_predicted_elapsed_time_ms(region_elapsed_time_ms);
2687 
2688 #if PREDICTIONS_VERBOSE
2689   size_t bytes_to_copy = predict_bytes_to_copy(hr);
2690   _inc_cset_predicted_bytes_to_copy += bytes_to_copy;
2691 
2692   // Record the number of bytes used in this region
2693   _inc_cset_recorded_young_bytes += used_bytes;
2694 
2695   // Cache the values we have added to the aggregated informtion
2696   // in the heap region in case we have to remove this region from
2697   // the incremental collection set, or it is updated by the
2698   // rset sampling code
2699   hr->set_predicted_bytes_to_copy(bytes_to_copy);
2700 #endif // PREDICTIONS_VERBOSE
2701 }
2702 
2703 void G1CollectorPolicy::remove_from_incremental_cset_info(HeapRegion* hr) {
2704   // This routine is currently only called as part of the updating of
2705   // existing policy information for regions in the incremental cset that
2706   // is performed by the concurrent refine thread(s) as part of young list
2707   // RSet sampling. Therefore we should not be at a safepoint.
2708 
2709   assert(!SafepointSynchronize::is_at_safepoint(), "should not be at safepoint");
2710   assert(hr->is_young(), "it should be");
2711 
2712   size_t used_bytes = hr->used();
2713   size_t old_rs_length = hr->recorded_rs_length();
2714   double old_elapsed_time_ms = hr->predicted_elapsed_time_ms();
2715 
2716   // Subtract the old recorded/predicted policy information for
2717   // the given heap region from the collection set info.
2718   _inc_cset_recorded_rs_lengths -= old_rs_length;
2719   _inc_cset_predicted_elapsed_time_ms -= old_elapsed_time_ms;
2720 
2721   _inc_cset_bytes_used_before -= used_bytes;
2722 
2723   // Clear the values cached in the heap region
2724   hr->set_recorded_rs_length(0);
2725   hr->set_predicted_elapsed_time_ms(0);
2726 
2727 #if PREDICTIONS_VERBOSE
2728   size_t old_predicted_bytes_to_copy = hr->predicted_bytes_to_copy();
2729   _inc_cset_predicted_bytes_to_copy -= old_predicted_bytes_to_copy;
2730 
2731   // Subtract the number of bytes used in this region
2732   _inc_cset_recorded_young_bytes -= used_bytes;
2733 
2734   // Clear the values cached in the heap region
2735   hr->set_predicted_bytes_to_copy(0);
2736 #endif // PREDICTIONS_VERBOSE
2737 }
2738 
2739 void G1CollectorPolicy::update_incremental_cset_info(HeapRegion* hr, size_t new_rs_length) {
2740   // Update the collection set information that is dependent on the new RS length
2741   assert(hr->is_young(), "Precondition");
2742 
2743   remove_from_incremental_cset_info(hr);
2744   add_to_incremental_cset_info(hr, new_rs_length);
2745 }
2746 
2747 void G1CollectorPolicy::add_region_to_incremental_cset_common(HeapRegion* hr) {
2748   assert( hr->is_young(), "invariant");
2749   assert( hr->young_index_in_cset() == -1, "invariant" );
2750   assert(_inc_cset_build_state == Active, "Precondition");
2751 
2752   // We need to clear and set the cached recorded/cached collection set
2753   // information in the heap region here (before the region gets added
2754   // to the collection set). An individual heap region's cached values
2755   // are calculated, aggregated with the policy collection set info,
2756   // and cached in the heap region here (initially) and (subsequently)
2757   // by the Young List sampling code.
2758 
2759   size_t rs_length = hr->rem_set()->occupied();
2760   add_to_incremental_cset_info(hr, rs_length);
2761 
2762   HeapWord* hr_end = hr->end();
2763   _inc_cset_max_finger = MAX2(_inc_cset_max_finger, hr_end);
2764 
2765   assert(!hr->in_collection_set(), "invariant");
2766   hr->set_in_collection_set(true);
2767   assert( hr->next_in_collection_set() == NULL, "invariant");
2768 
2769   _inc_cset_size++;
2770   _g1->register_region_with_in_cset_fast_test(hr);
2771 
2772   hr->set_young_index_in_cset((int) _inc_cset_young_index);
2773   ++_inc_cset_young_index;
2774 }
2775 
2776 // Add the region at the RHS of the incremental cset
2777 void G1CollectorPolicy::add_region_to_incremental_cset_rhs(HeapRegion* hr) {
2778   // We should only ever be appending survivors at the end of a pause
2779   assert( hr->is_survivor(), "Logic");
2780 
2781   // Do the 'common' stuff
2782   add_region_to_incremental_cset_common(hr);
2783 
2784   // Now add the region at the right hand side
2785   if (_inc_cset_tail == NULL) {
2786     assert(_inc_cset_head == NULL, "invariant");
2787     _inc_cset_head = hr;
2788   } else {
2789     _inc_cset_tail->set_next_in_collection_set(hr);
2790   }
2791   _inc_cset_tail = hr;
2792 
2793   if (G1PrintHeapRegions) {
2794     gclog_or_tty->print_cr(" added region to incremental cset (RHS) "
2795                   "%d:["PTR_FORMAT", "PTR_FORMAT"], "
2796                   "top "PTR_FORMAT", young %s",
2797                   hr->hrs_index(), hr->bottom(), hr->end(),
2798                   hr->top(), (hr->is_young()) ? "YES" : "NO");
2799   }
2800 }
2801 
2802 // Add the region to the LHS of the incremental cset
2803 void G1CollectorPolicy::add_region_to_incremental_cset_lhs(HeapRegion* hr) {
2804   // Survivors should be added to the RHS at the end of a pause
2805   assert(!hr->is_survivor(), "Logic");
2806 
2807   // Do the 'common' stuff
2808   add_region_to_incremental_cset_common(hr);
2809 
2810   // Add the region at the left hand side
2811   hr->set_next_in_collection_set(_inc_cset_head);
2812   if (_inc_cset_head == NULL) {
2813     assert(_inc_cset_tail == NULL, "Invariant");
2814     _inc_cset_tail = hr;
2815   }
2816   _inc_cset_head = hr;
2817 
2818   if (G1PrintHeapRegions) {
2819     gclog_or_tty->print_cr(" added region to incremental cset (LHS) "
2820                   "%d:["PTR_FORMAT", "PTR_FORMAT"], "
2821                   "top "PTR_FORMAT", young %s",
2822                   hr->hrs_index(), hr->bottom(), hr->end(),
2823                   hr->top(), (hr->is_young()) ? "YES" : "NO");
2824   }
2825 }
2826 
2827 #ifndef PRODUCT
2828 void G1CollectorPolicy::print_collection_set(HeapRegion* list_head, outputStream* st) {
2829   assert(list_head == inc_cset_head() || list_head == collection_set(), "must be");
2830 
2831   st->print_cr("\nCollection_set:");
2832   HeapRegion* csr = list_head;
2833   while (csr != NULL) {
2834     HeapRegion* next = csr->next_in_collection_set();
2835     assert(csr->in_collection_set(), "bad CS");
2836     st->print_cr("  [%08x-%08x], t: %08x, P: %08x, N: %08x, C: %08x, "
2837                  "age: %4d, y: %d, surv: %d",
2838                         csr->bottom(), csr->end(),
2839                         csr->top(),
2840                         csr->prev_top_at_mark_start(),
2841                         csr->next_top_at_mark_start(),
2842                         csr->top_at_conc_mark_count(),
2843                         csr->age_in_surv_rate_group_cond(),
2844                         csr->is_young(),
2845                         csr->is_survivor());
2846     csr = next;
2847   }
2848 }
2849 #endif // !PRODUCT
2850 
2851 void
2852 G1CollectorPolicy_BestRegionsFirst::choose_collection_set(
2853                                                   double target_pause_time_ms) {
2854   // Set this here - in case we're not doing young collections.
2855   double non_young_start_time_sec = os::elapsedTime();
2856 
2857   start_recording_regions();
2858 
2859   guarantee(target_pause_time_ms > 0.0,
2860             err_msg("target_pause_time_ms = %1.6lf should be positive",
2861                     target_pause_time_ms));
2862   guarantee(_collection_set == NULL, "Precondition");
2863 
2864   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
2865   double predicted_pause_time_ms = base_time_ms;
2866 
2867   double time_remaining_ms = target_pause_time_ms - base_time_ms;
2868 
2869   // the 10% and 50% values are arbitrary...
2870   if (time_remaining_ms < 0.10 * target_pause_time_ms) {
2871     time_remaining_ms = 0.50 * target_pause_time_ms;
2872     _within_target = false;
2873   } else {
2874     _within_target = true;
2875   }
2876 
2877   // We figure out the number of bytes available for future to-space.
2878   // For new regions without marking information, we must assume the
2879   // worst-case of complete survival.  If we have marking information for a
2880   // region, we can bound the amount of live data.  We can add a number of
2881   // such regions, as long as the sum of the live data bounds does not
2882   // exceed the available evacuation space.
2883   size_t max_live_bytes = _g1->free_regions() * HeapRegion::GrainBytes;
2884 
2885   size_t expansion_bytes =
2886     _g1->expansion_regions() * HeapRegion::GrainBytes;
2887 
2888   _collection_set_bytes_used_before = 0;
2889   _collection_set_size = 0;
2890 
2891   // Adjust for expansion and slop.
2892   max_live_bytes = max_live_bytes + expansion_bytes;
2893 
2894   assert(_g1->regions_accounted_for(), "Region leakage!");
2895 
2896   HeapRegion* hr;
2897   if (in_young_gc_mode()) {
2898     double young_start_time_sec = os::elapsedTime();
2899 
2900     if (G1PolicyVerbose > 0) {
2901       gclog_or_tty->print_cr("Adding %d young regions to the CSet",
2902                     _g1->young_list()->length());
2903     }
2904 
2905     _young_cset_length  = 0;
2906     _last_young_gc_full = full_young_gcs() ? true : false;
2907 
2908     if (_last_young_gc_full)
2909       ++_full_young_pause_num;
2910     else
2911       ++_partial_young_pause_num;
2912 
2913     // The young list is laid with the survivor regions from the previous
2914     // pause are appended to the RHS of the young list, i.e.
2915     //   [Newly Young Regions ++ Survivors from last pause].
2916 
2917     hr = _g1->young_list()->first_survivor_region();
2918     while (hr != NULL) {
2919       assert(hr->is_survivor(), "badly formed young list");
2920       hr->set_young();
2921       hr = hr->get_next_young_region();
2922     }
2923 
2924     // Clear the fields that point to the survivor list - they are
2925     // all young now.
2926     _g1->young_list()->clear_survivors();
2927 
2928     if (_g1->mark_in_progress())
2929       _g1->concurrent_mark()->register_collection_set_finger(_inc_cset_max_finger);
2930 
2931     _young_cset_length = _inc_cset_young_index;
2932     _collection_set = _inc_cset_head;
2933     _collection_set_size = _inc_cset_size;
2934     _collection_set_bytes_used_before = _inc_cset_bytes_used_before;
2935 
2936     // For young regions in the collection set, we assume the worst
2937     // case of complete survival
2938     max_live_bytes -= _inc_cset_size * HeapRegion::GrainBytes;
2939 
2940     time_remaining_ms -= _inc_cset_predicted_elapsed_time_ms;
2941     predicted_pause_time_ms += _inc_cset_predicted_elapsed_time_ms;
2942 
2943     // The number of recorded young regions is the incremental
2944     // collection set's current size
2945     set_recorded_young_regions(_inc_cset_size);
2946     set_recorded_rs_lengths(_inc_cset_recorded_rs_lengths);
2947     set_recorded_young_bytes(_inc_cset_recorded_young_bytes);
2948 #if PREDICTIONS_VERBOSE
2949     set_predicted_bytes_to_copy(_inc_cset_predicted_bytes_to_copy);
2950 #endif // PREDICTIONS_VERBOSE
2951 
2952     if (G1PolicyVerbose > 0) {
2953       gclog_or_tty->print_cr("  Added " PTR_FORMAT " Young Regions to CS.",
2954                              _inc_cset_size);
2955       gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
2956                             max_live_bytes/K);
2957     }
2958 
2959     assert(_inc_cset_size == _g1->young_list()->length(), "Invariant");
2960 
2961     double young_end_time_sec = os::elapsedTime();
2962     _recorded_young_cset_choice_time_ms =
2963       (young_end_time_sec - young_start_time_sec) * 1000.0;
2964 
2965     // We are doing young collections so reset this.
2966     non_young_start_time_sec = young_end_time_sec;
2967 
2968     // Note we can use either _collection_set_size or
2969     // _young_cset_length here
2970     if (_collection_set_size > 0 && _last_young_gc_full) {
2971       // don't bother adding more regions...
2972       goto choose_collection_set_end;
2973     }
2974   }
2975 
2976   if (!in_young_gc_mode() || !full_young_gcs()) {
2977     bool should_continue = true;
2978     NumberSeq seq;
2979     double avg_prediction = 100000000000000000.0; // something very large
2980 
2981     do {
2982       hr = _collectionSetChooser->getNextMarkedRegion(time_remaining_ms,
2983                                                       avg_prediction);
2984       if (hr != NULL) {
2985         double predicted_time_ms = predict_region_elapsed_time_ms(hr, false);
2986         time_remaining_ms -= predicted_time_ms;
2987         predicted_pause_time_ms += predicted_time_ms;
2988         add_to_collection_set(hr);
2989         record_non_young_cset_region(hr);
2990         max_live_bytes -= MIN2(hr->max_live_bytes(), max_live_bytes);
2991         if (G1PolicyVerbose > 0) {
2992           gclog_or_tty->print_cr("    (" SIZE_FORMAT " KB left in heap.)",
2993                         max_live_bytes/K);
2994         }
2995         seq.add(predicted_time_ms);
2996         avg_prediction = seq.avg() + seq.sd();
2997       }
2998       should_continue =
2999         ( hr != NULL) &&
3000         ( (adaptive_young_list_length()) ? time_remaining_ms > 0.0
3001           : _collection_set_size < _young_list_fixed_length );
3002     } while (should_continue);
3003 
3004     if (!adaptive_young_list_length() &&
3005         _collection_set_size < _young_list_fixed_length)
3006       _should_revert_to_full_young_gcs  = true;
3007   }
3008 
3009 choose_collection_set_end:
3010   stop_incremental_cset_building();
3011 
3012   count_CS_bytes_used();
3013 
3014   end_recording_regions();
3015 
3016   double non_young_end_time_sec = os::elapsedTime();
3017   _recorded_non_young_cset_choice_time_ms =
3018     (non_young_end_time_sec - non_young_start_time_sec) * 1000.0;
3019 }
3020 
3021 void G1CollectorPolicy_BestRegionsFirst::record_full_collection_end() {
3022   G1CollectorPolicy::record_full_collection_end();
3023   _collectionSetChooser->updateAfterFullCollection();
3024 }
3025 
3026 void G1CollectorPolicy_BestRegionsFirst::
3027 expand_if_possible(size_t numRegions) {
3028   size_t expansion_bytes = numRegions * HeapRegion::GrainBytes;
3029   _g1->expand(expansion_bytes);
3030 }
3031 
3032 void G1CollectorPolicy_BestRegionsFirst::
3033 record_collection_pause_end() {
3034   G1CollectorPolicy::record_collection_pause_end();
3035   assert(assertMarkedBytesDataOK(), "Marked regions not OK at pause end.");
3036 }