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