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