1 /*
   2  * Copyright (c) 2001, 2016, 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/g1/concurrentG1Refine.hpp"
  27 #include "gc/g1/concurrentMarkThread.inline.hpp"
  28 #include "gc/g1/g1Analytics.hpp"
  29 #include "gc/g1/g1CollectedHeap.inline.hpp"
  30 #include "gc/g1/g1CollectionSet.hpp"
  31 #include "gc/g1/g1CollectorPolicy.hpp"
  32 #include "gc/g1/g1ConcurrentMark.hpp"
  33 #include "gc/g1/g1IHOPControl.hpp"
  34 #include "gc/g1/g1GCPhaseTimes.hpp"
  35 #include "gc/g1/g1YoungGenSizer.hpp"
  36 #include "gc/g1/heapRegion.inline.hpp"
  37 #include "gc/g1/heapRegionRemSet.hpp"
  38 #include "gc/shared/gcPolicyCounters.hpp"
  39 #include "runtime/arguments.hpp"
  40 #include "runtime/java.hpp"
  41 #include "runtime/mutexLocker.hpp"
  42 #include "utilities/debug.hpp"
  43 #include "utilities/pair.hpp"
  44 
  45 G1CollectorPolicy::G1CollectorPolicy() :
  46   _predictor(G1ConfidencePercent / 100.0),
  47   _analytics(new G1Analytics(&_predictor)),
  48   _pause_time_target_ms((double) MaxGCPauseMillis),
  49   _rs_lengths_prediction(0),
  50   _max_survivor_regions(0),
  51   _survivors_age_table(true),
  52 
  53   _bytes_allocated_in_old_since_last_gc(0),
  54   _ihop_control(NULL),
  55   _initial_mark_to_mixed() {
  56 
  57   // SurvRateGroups below must be initialized after the predictor because they
  58   // indirectly use it through this object passed to their constructor.
  59   _short_lived_surv_rate_group =
  60     new SurvRateGroup(&_predictor, "Short Lived", G1YoungSurvRateNumRegionsSummary);
  61   _survivor_surv_rate_group =
  62     new SurvRateGroup(&_predictor, "Survivor", G1YoungSurvRateNumRegionsSummary);
  63 
  64   // Set up the region size and associated fields. Given that the
  65   // policy is created before the heap, we have to set this up here,
  66   // so it's done as soon as possible.
  67 
  68   // It would have been natural to pass initial_heap_byte_size() and
  69   // max_heap_byte_size() to setup_heap_region_size() but those have
  70   // not been set up at this point since they should be aligned with
  71   // the region size. So, there is a circular dependency here. We base
  72   // the region size on the heap size, but the heap size should be
  73   // aligned with the region size. To get around this we use the
  74   // unaligned values for the heap.
  75   HeapRegion::setup_heap_region_size(InitialHeapSize, MaxHeapSize);
  76   HeapRegionRemSet::setup_remset_size();
  77 
  78   _phase_times = new G1GCPhaseTimes(ParallelGCThreads);
  79 
  80   // Below, we might need to calculate the pause time target based on
  81   // the pause interval. When we do so we are going to give G1 maximum
  82   // flexibility and allow it to do pauses when it needs to. So, we'll
  83   // arrange that the pause interval to be pause time target + 1 to
  84   // ensure that a) the pause time target is maximized with respect to
  85   // the pause interval and b) we maintain the invariant that pause
  86   // time target < pause interval. If the user does not want this
  87   // maximum flexibility, they will have to set the pause interval
  88   // explicitly.
  89 
  90   // First make sure that, if either parameter is set, its value is
  91   // reasonable.
  92   if (!FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
  93     if (MaxGCPauseMillis < 1) {
  94       vm_exit_during_initialization("MaxGCPauseMillis should be "
  95                                     "greater than 0");
  96     }
  97   }
  98   if (!FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
  99     if (GCPauseIntervalMillis < 1) {
 100       vm_exit_during_initialization("GCPauseIntervalMillis should be "
 101                                     "greater than 0");
 102     }
 103   }
 104 
 105   // Then, if the pause time target parameter was not set, set it to
 106   // the default value.
 107   if (FLAG_IS_DEFAULT(MaxGCPauseMillis)) {
 108     if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
 109       // The default pause time target in G1 is 200ms
 110       FLAG_SET_DEFAULT(MaxGCPauseMillis, 200);
 111     } else {
 112       // We do not allow the pause interval to be set without the
 113       // pause time target
 114       vm_exit_during_initialization("GCPauseIntervalMillis cannot be set "
 115                                     "without setting MaxGCPauseMillis");
 116     }
 117   }
 118 
 119   // Then, if the interval parameter was not set, set it according to
 120   // the pause time target (this will also deal with the case when the
 121   // pause time target is the default value).
 122   if (FLAG_IS_DEFAULT(GCPauseIntervalMillis)) {
 123     FLAG_SET_DEFAULT(GCPauseIntervalMillis, MaxGCPauseMillis + 1);
 124   }
 125 
 126   // Finally, make sure that the two parameters are consistent.
 127   if (MaxGCPauseMillis >= GCPauseIntervalMillis) {
 128     char buffer[256];
 129     jio_snprintf(buffer, 256,
 130                  "MaxGCPauseMillis (%u) should be less than "
 131                  "GCPauseIntervalMillis (%u)",
 132                  MaxGCPauseMillis, GCPauseIntervalMillis);
 133     vm_exit_during_initialization(buffer);
 134   }
 135 
 136   double max_gc_time = (double) MaxGCPauseMillis / 1000.0;
 137   double time_slice  = (double) GCPauseIntervalMillis / 1000.0;
 138   _mmu_tracker = new G1MMUTrackerQueue(time_slice, max_gc_time);
 139 
 140   _tenuring_threshold = MaxTenuringThreshold;
 141 
 142 
 143   uintx reserve_perc = G1ReservePercent;
 144   // Put an artificial ceiling on this so that it's not set to a silly value.
 145   if (reserve_perc > 50) {
 146     reserve_perc = 50;
 147     warning("G1ReservePercent is set to a value that is too large, "
 148             "it's been updated to " UINTX_FORMAT, reserve_perc);
 149   }
 150   _reserve_factor = (double) reserve_perc / 100.0;
 151   // This will be set when the heap is expanded
 152   // for the first time during initialization.
 153   _reserve_regions = 0;
 154 
 155   _ihop_control = create_ihop_control();
 156 }
 157 
 158 G1CollectorPolicy::~G1CollectorPolicy() {
 159   delete _ihop_control;
 160 }
 161 
 162 void G1CollectorPolicy::initialize_alignments() {
 163   _space_alignment = HeapRegion::GrainBytes;
 164   size_t card_table_alignment = CardTableRS::ct_max_alignment_constraint();
 165   size_t page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
 166   _heap_alignment = MAX3(card_table_alignment, _space_alignment, page_size);
 167 }
 168 
 169 G1CollectorState* G1CollectorPolicy::collector_state() const { return _g1->collector_state(); }
 170 
 171 void G1CollectorPolicy::post_heap_initialize() {
 172   uintx max_regions = G1CollectedHeap::heap()->max_regions();
 173   size_t max_young_size = (size_t)_young_gen_sizer->max_young_length(max_regions) * HeapRegion::GrainBytes;
 174   if (max_young_size != MaxNewSize) {
 175     FLAG_SET_ERGO(size_t, MaxNewSize, max_young_size);
 176   }
 177 }
 178 
 179 void G1CollectorPolicy::initialize_flags() {
 180   if (G1HeapRegionSize != HeapRegion::GrainBytes) {
 181     FLAG_SET_ERGO(size_t, G1HeapRegionSize, HeapRegion::GrainBytes);
 182   }
 183 
 184   if (SurvivorRatio < 1) {
 185     vm_exit_during_initialization("Invalid survivor ratio specified");
 186   }
 187   CollectorPolicy::initialize_flags();
 188   _young_gen_sizer = new G1YoungGenSizer(); // Must be after call to initialize_flags
 189 }
 190 
 191 
 192 void G1CollectorPolicy::init() {
 193   // Set aside an initial future to_space.
 194   _g1 = G1CollectedHeap::heap();
 195   _collection_set = _g1->collection_set();
 196   _collection_set->set_policy(this);
 197 
 198   assert(Heap_lock->owned_by_self(), "Locking discipline.");
 199 
 200   initialize_gc_policy_counters();
 201 
 202   if (adaptive_young_list_length()) {
 203     _young_list_fixed_length = 0;
 204   } else {
 205     _young_list_fixed_length = _young_gen_sizer->min_desired_young_length();
 206   }
 207   _free_regions_at_end_of_collection = _g1->num_free_regions();
 208 
 209   update_young_list_max_and_target_length();
 210   // We may immediately start allocating regions and placing them on the
 211   // collection set list. Initialize the per-collection set info
 212   _collection_set->start_incremental_building();
 213 }
 214 
 215 void G1CollectorPolicy::note_gc_start(uint num_active_workers) {
 216   phase_times()->note_gc_start(num_active_workers);
 217 }
 218 
 219 // Create the jstat counters for the policy.
 220 void G1CollectorPolicy::initialize_gc_policy_counters() {
 221   _gc_policy_counters = new GCPolicyCounters("GarbageFirst", 1, 3);
 222 }
 223 
 224 bool G1CollectorPolicy::predict_will_fit(uint young_length,
 225                                          double base_time_ms,
 226                                          uint base_free_regions,
 227                                          double target_pause_time_ms) const {
 228   if (young_length >= base_free_regions) {
 229     // end condition 1: not enough space for the young regions
 230     return false;
 231   }
 232 
 233   double accum_surv_rate = accum_yg_surv_rate_pred((int) young_length - 1);
 234   size_t bytes_to_copy =
 235                (size_t) (accum_surv_rate * (double) HeapRegion::GrainBytes);
 236   double copy_time_ms = _analytics->predict_object_copy_time_ms(bytes_to_copy,
 237                                                                 collector_state()->during_concurrent_mark());
 238   double young_other_time_ms = _analytics->predict_young_other_time_ms(young_length);
 239   double pause_time_ms = base_time_ms + copy_time_ms + young_other_time_ms;
 240   if (pause_time_ms > target_pause_time_ms) {
 241     // end condition 2: prediction is over the target pause time
 242     return false;
 243   }
 244 
 245   size_t free_bytes = (base_free_regions - young_length) * HeapRegion::GrainBytes;
 246 
 247   // When copying, we will likely need more bytes free than is live in the region.
 248   // Add some safety margin to factor in the confidence of our guess, and the
 249   // natural expected waste.
 250   // (100.0 / G1ConfidencePercent) is a scale factor that expresses the uncertainty
 251   // of the calculation: the lower the confidence, the more headroom.
 252   // (100 + TargetPLABWastePct) represents the increase in expected bytes during
 253   // copying due to anticipated waste in the PLABs.
 254   double safety_factor = (100.0 / G1ConfidencePercent) * (100 + TargetPLABWastePct) / 100.0;
 255   size_t expected_bytes_to_copy = (size_t)(safety_factor * bytes_to_copy);
 256 
 257   if (expected_bytes_to_copy > free_bytes) {
 258     // end condition 3: out-of-space
 259     return false;
 260   }
 261 
 262   // success!
 263   return true;
 264 }
 265 
 266 void G1CollectorPolicy::record_new_heap_size(uint new_number_of_regions) {
 267   // re-calculate the necessary reserve
 268   double reserve_regions_d = (double) new_number_of_regions * _reserve_factor;
 269   // We use ceiling so that if reserve_regions_d is > 0.0 (but
 270   // smaller than 1.0) we'll get 1.
 271   _reserve_regions = (uint) ceil(reserve_regions_d);
 272 
 273   _young_gen_sizer->heap_size_changed(new_number_of_regions);
 274 
 275   _ihop_control->update_target_occupancy(new_number_of_regions * HeapRegion::GrainBytes);
 276 }
 277 
 278 uint G1CollectorPolicy::calculate_young_list_desired_min_length(
 279                                                        uint base_min_length) const {
 280   uint desired_min_length = 0;
 281   if (adaptive_young_list_length()) {
 282     if (_analytics->num_alloc_rate_ms() > 3) {
 283       double now_sec = os::elapsedTime();
 284       double when_ms = _mmu_tracker->when_max_gc_sec(now_sec) * 1000.0;
 285       double alloc_rate_ms = _analytics->predict_alloc_rate_ms();
 286       desired_min_length = (uint) ceil(alloc_rate_ms * when_ms);
 287     } else {
 288       // otherwise we don't have enough info to make the prediction
 289     }
 290   }
 291   desired_min_length += base_min_length;
 292   // make sure we don't go below any user-defined minimum bound
 293   return MAX2(_young_gen_sizer->min_desired_young_length(), desired_min_length);
 294 }
 295 
 296 uint G1CollectorPolicy::calculate_young_list_desired_max_length() const {
 297   // Here, we might want to also take into account any additional
 298   // constraints (i.e., user-defined minimum bound). Currently, we
 299   // effectively don't set this bound.
 300   return _young_gen_sizer->max_desired_young_length();
 301 }
 302 
 303 uint G1CollectorPolicy::update_young_list_max_and_target_length() {
 304   return update_young_list_max_and_target_length(_analytics->predict_rs_lengths());
 305 }
 306 
 307 uint G1CollectorPolicy::update_young_list_max_and_target_length(size_t rs_lengths) {
 308   uint unbounded_target_length = update_young_list_target_length(rs_lengths);
 309   update_max_gc_locker_expansion();
 310   return unbounded_target_length;
 311 }
 312 
 313 uint G1CollectorPolicy::update_young_list_target_length(size_t rs_lengths) {
 314   YoungTargetLengths young_lengths = young_list_target_lengths(rs_lengths);
 315   _young_list_target_length = young_lengths.first;
 316   return young_lengths.second;
 317 }
 318 
 319 G1CollectorPolicy::YoungTargetLengths G1CollectorPolicy::young_list_target_lengths(size_t rs_lengths) const {
 320   YoungTargetLengths result;
 321 
 322   // Calculate the absolute and desired min bounds first.
 323 
 324   // This is how many young regions we already have (currently: the survivors).
 325   const uint base_min_length = _g1->young_list()->survivor_length();
 326   uint desired_min_length = calculate_young_list_desired_min_length(base_min_length);
 327   // This is the absolute minimum young length. Ensure that we
 328   // will at least have one eden region available for allocation.
 329   uint absolute_min_length = base_min_length + MAX2(_g1->young_list()->eden_length(), (uint)1);
 330   // If we shrank the young list target it should not shrink below the current size.
 331   desired_min_length = MAX2(desired_min_length, absolute_min_length);
 332   // Calculate the absolute and desired max bounds.
 333 
 334   uint desired_max_length = calculate_young_list_desired_max_length();
 335 
 336   uint young_list_target_length = 0;
 337   if (adaptive_young_list_length()) {
 338     if (collector_state()->gcs_are_young()) {
 339       young_list_target_length =
 340                         calculate_young_list_target_length(rs_lengths,
 341                                                            base_min_length,
 342                                                            desired_min_length,
 343                                                            desired_max_length);
 344     } else {
 345       // Don't calculate anything and let the code below bound it to
 346       // the desired_min_length, i.e., do the next GC as soon as
 347       // possible to maximize how many old regions we can add to it.
 348     }
 349   } else {
 350     // The user asked for a fixed young gen so we'll fix the young gen
 351     // whether the next GC is young or mixed.
 352     young_list_target_length = _young_list_fixed_length;
 353   }
 354 
 355   result.second = young_list_target_length;
 356 
 357   // We will try our best not to "eat" into the reserve.
 358   uint absolute_max_length = 0;
 359   if (_free_regions_at_end_of_collection > _reserve_regions) {
 360     absolute_max_length = _free_regions_at_end_of_collection - _reserve_regions;
 361   }
 362   if (desired_max_length > absolute_max_length) {
 363     desired_max_length = absolute_max_length;
 364   }
 365 
 366   // Make sure we don't go over the desired max length, nor under the
 367   // desired min length. In case they clash, desired_min_length wins
 368   // which is why that test is second.
 369   if (young_list_target_length > desired_max_length) {
 370     young_list_target_length = desired_max_length;
 371   }
 372   if (young_list_target_length < desired_min_length) {
 373     young_list_target_length = desired_min_length;
 374   }
 375 
 376   assert(young_list_target_length > base_min_length,
 377          "we should be able to allocate at least one eden region");
 378   assert(young_list_target_length >= absolute_min_length, "post-condition");
 379 
 380   result.first = young_list_target_length;
 381   return result;
 382 }
 383 
 384 uint
 385 G1CollectorPolicy::calculate_young_list_target_length(size_t rs_lengths,
 386                                                      uint base_min_length,
 387                                                      uint desired_min_length,
 388                                                      uint desired_max_length) const {
 389   assert(adaptive_young_list_length(), "pre-condition");
 390   assert(collector_state()->gcs_are_young(), "only call this for young GCs");
 391 
 392   // In case some edge-condition makes the desired max length too small...
 393   if (desired_max_length <= desired_min_length) {
 394     return desired_min_length;
 395   }
 396 
 397   // We'll adjust min_young_length and max_young_length not to include
 398   // the already allocated young regions (i.e., so they reflect the
 399   // min and max eden regions we'll allocate). The base_min_length
 400   // will be reflected in the predictions by the
 401   // survivor_regions_evac_time prediction.
 402   assert(desired_min_length > base_min_length, "invariant");
 403   uint min_young_length = desired_min_length - base_min_length;
 404   assert(desired_max_length > base_min_length, "invariant");
 405   uint max_young_length = desired_max_length - base_min_length;
 406 
 407   double target_pause_time_ms = _mmu_tracker->max_gc_time() * 1000.0;
 408   double survivor_regions_evac_time = predict_survivor_regions_evac_time();
 409   size_t pending_cards = _analytics->predict_pending_cards();
 410   size_t adj_rs_lengths = rs_lengths + _analytics->predict_rs_length_diff();
 411   size_t scanned_cards = _analytics->predict_card_num(adj_rs_lengths, /* gcs_are_young */ true);
 412   double base_time_ms =
 413     predict_base_elapsed_time_ms(pending_cards, scanned_cards) +
 414     survivor_regions_evac_time;
 415   uint available_free_regions = _free_regions_at_end_of_collection;
 416   uint base_free_regions = 0;
 417   if (available_free_regions > _reserve_regions) {
 418     base_free_regions = available_free_regions - _reserve_regions;
 419   }
 420 
 421   // Here, we will make sure that the shortest young length that
 422   // makes sense fits within the target pause time.
 423 
 424   if (predict_will_fit(min_young_length, base_time_ms,
 425                        base_free_regions, target_pause_time_ms)) {
 426     // The shortest young length will fit into the target pause time;
 427     // we'll now check whether the absolute maximum number of young
 428     // regions will fit in the target pause time. If not, we'll do
 429     // a binary search between min_young_length and max_young_length.
 430     if (predict_will_fit(max_young_length, base_time_ms,
 431                          base_free_regions, target_pause_time_ms)) {
 432       // The maximum young length will fit into the target pause time.
 433       // We are done so set min young length to the maximum length (as
 434       // the result is assumed to be returned in min_young_length).
 435       min_young_length = max_young_length;
 436     } else {
 437       // The maximum possible number of young regions will not fit within
 438       // the target pause time so we'll search for the optimal
 439       // length. The loop invariants are:
 440       //
 441       // min_young_length < max_young_length
 442       // min_young_length is known to fit into the target pause time
 443       // max_young_length is known not to fit into the target pause time
 444       //
 445       // Going into the loop we know the above hold as we've just
 446       // checked them. Every time around the loop we check whether
 447       // the middle value between min_young_length and
 448       // max_young_length fits into the target pause time. If it
 449       // does, it becomes the new min. If it doesn't, it becomes
 450       // the new max. This way we maintain the loop invariants.
 451 
 452       assert(min_young_length < max_young_length, "invariant");
 453       uint diff = (max_young_length - min_young_length) / 2;
 454       while (diff > 0) {
 455         uint young_length = min_young_length + diff;
 456         if (predict_will_fit(young_length, base_time_ms,
 457                              base_free_regions, target_pause_time_ms)) {
 458           min_young_length = young_length;
 459         } else {
 460           max_young_length = young_length;
 461         }
 462         assert(min_young_length <  max_young_length, "invariant");
 463         diff = (max_young_length - min_young_length) / 2;
 464       }
 465       // The results is min_young_length which, according to the
 466       // loop invariants, should fit within the target pause time.
 467 
 468       // These are the post-conditions of the binary search above:
 469       assert(min_young_length < max_young_length,
 470              "otherwise we should have discovered that max_young_length "
 471              "fits into the pause target and not done the binary search");
 472       assert(predict_will_fit(min_young_length, base_time_ms,
 473                               base_free_regions, target_pause_time_ms),
 474              "min_young_length, the result of the binary search, should "
 475              "fit into the pause target");
 476       assert(!predict_will_fit(min_young_length + 1, base_time_ms,
 477                                base_free_regions, target_pause_time_ms),
 478              "min_young_length, the result of the binary search, should be "
 479              "optimal, so no larger length should fit into the pause target");
 480     }
 481   } else {
 482     // Even the minimum length doesn't fit into the pause time
 483     // target, return it as the result nevertheless.
 484   }
 485   return base_min_length + min_young_length;
 486 }
 487 
 488 double G1CollectorPolicy::predict_survivor_regions_evac_time() const {
 489   double survivor_regions_evac_time = 0.0;
 490   for (HeapRegion * r = _g1->young_list()->first_survivor_region();
 491        r != NULL && r != _g1->young_list()->last_survivor_region()->get_next_young_region();
 492        r = r->get_next_young_region()) {
 493     survivor_regions_evac_time += predict_region_elapsed_time_ms(r, collector_state()->gcs_are_young());
 494   }
 495   return survivor_regions_evac_time;
 496 }
 497 
 498 void G1CollectorPolicy::revise_young_list_target_length_if_necessary(size_t rs_lengths) {
 499   guarantee( adaptive_young_list_length(), "should not call this otherwise" );
 500 
 501   if (rs_lengths > _rs_lengths_prediction) {
 502     // add 10% to avoid having to recalculate often
 503     size_t rs_lengths_prediction = rs_lengths * 1100 / 1000;
 504     update_rs_lengths_prediction(rs_lengths_prediction);
 505 
 506     update_young_list_max_and_target_length(rs_lengths_prediction);
 507   }
 508 }
 509 
 510 void G1CollectorPolicy::update_rs_lengths_prediction() {
 511   update_rs_lengths_prediction(_analytics->predict_rs_lengths());
 512 }
 513 
 514 void G1CollectorPolicy::update_rs_lengths_prediction(size_t prediction) {
 515   if (collector_state()->gcs_are_young() && adaptive_young_list_length()) {
 516     _rs_lengths_prediction = prediction;
 517   }
 518 }
 519 
 520 #ifndef PRODUCT
 521 bool G1CollectorPolicy::verify_young_ages() {
 522   HeapRegion* head = _g1->young_list()->first_region();
 523   return
 524     verify_young_ages(head, _short_lived_surv_rate_group);
 525   // also call verify_young_ages on any additional surv rate groups
 526 }
 527 
 528 bool
 529 G1CollectorPolicy::verify_young_ages(HeapRegion* head,
 530                                      SurvRateGroup *surv_rate_group) {
 531   guarantee( surv_rate_group != NULL, "pre-condition" );
 532 
 533   const char* name = surv_rate_group->name();
 534   bool ret = true;
 535   int prev_age = -1;
 536 
 537   for (HeapRegion* curr = head;
 538        curr != NULL;
 539        curr = curr->get_next_young_region()) {
 540     SurvRateGroup* group = curr->surv_rate_group();
 541     if (group == NULL && !curr->is_survivor()) {
 542       log_error(gc, verify)("## %s: encountered NULL surv_rate_group", name);
 543       ret = false;
 544     }
 545 
 546     if (surv_rate_group == group) {
 547       int age = curr->age_in_surv_rate_group();
 548 
 549       if (age < 0) {
 550         log_error(gc, verify)("## %s: encountered negative age", name);
 551         ret = false;
 552       }
 553 
 554       if (age <= prev_age) {
 555         log_error(gc, verify)("## %s: region ages are not strictly increasing (%d, %d)", name, age, prev_age);
 556         ret = false;
 557       }
 558       prev_age = age;
 559     }
 560   }
 561 
 562   return ret;
 563 }
 564 #endif // PRODUCT
 565 
 566 void G1CollectorPolicy::record_full_collection_start() {
 567   _full_collection_start_sec = os::elapsedTime();
 568   // Release the future to-space so that it is available for compaction into.
 569   collector_state()->set_full_collection(true);
 570 }
 571 
 572 void G1CollectorPolicy::record_full_collection_end() {
 573   // Consider this like a collection pause for the purposes of allocation
 574   // since last pause.
 575   double end_sec = os::elapsedTime();
 576   double full_gc_time_sec = end_sec - _full_collection_start_sec;
 577   double full_gc_time_ms = full_gc_time_sec * 1000.0;
 578 
 579   _analytics->update_recent_gc_times(end_sec, full_gc_time_ms);
 580 
 581   collector_state()->set_full_collection(false);
 582 
 583   // "Nuke" the heuristics that control the young/mixed GC
 584   // transitions and make sure we start with young GCs after the Full GC.
 585   collector_state()->set_gcs_are_young(true);
 586   collector_state()->set_last_young_gc(false);
 587   collector_state()->set_initiate_conc_mark_if_possible(need_to_start_conc_mark("end of Full GC", 0));
 588   collector_state()->set_during_initial_mark_pause(false);
 589   collector_state()->set_in_marking_window(false);
 590   collector_state()->set_in_marking_window_im(false);
 591 
 592   _short_lived_surv_rate_group->start_adding_regions();
 593   // also call this on any additional surv rate groups
 594 
 595   _free_regions_at_end_of_collection = _g1->num_free_regions();
 596   // Reset survivors SurvRateGroup.
 597   _survivor_surv_rate_group->reset();
 598   update_young_list_max_and_target_length();
 599   update_rs_lengths_prediction();
 600   cset_chooser()->clear();
 601 
 602   _bytes_allocated_in_old_since_last_gc = 0;
 603 
 604   record_pause(FullGC, _full_collection_start_sec, end_sec);
 605 }
 606 
 607 void G1CollectorPolicy::record_collection_pause_start(double start_time_sec) {
 608   // We only need to do this here as the policy will only be applied
 609   // to the GC we're about to start. so, no point is calculating this
 610   // every time we calculate / recalculate the target young length.
 611   update_survivors_policy();
 612 
 613   assert(_g1->used() == _g1->recalculate_used(),
 614          "sanity, used: " SIZE_FORMAT " recalculate_used: " SIZE_FORMAT,
 615          _g1->used(), _g1->recalculate_used());
 616 
 617   phase_times()->record_cur_collection_start_sec(start_time_sec);
 618   _pending_cards = _g1->pending_card_num();
 619 
 620   _collection_set->reset_bytes_used_before();
 621   _bytes_copied_during_gc = 0;
 622 
 623   collector_state()->set_last_gc_was_young(false);
 624 
 625   // do that for any other surv rate groups
 626   _short_lived_surv_rate_group->stop_adding_regions();
 627   _survivors_age_table.clear();
 628 
 629   assert( verify_young_ages(), "region age verification" );
 630 }
 631 
 632 void G1CollectorPolicy::record_concurrent_mark_init_end(double
 633                                                    mark_init_elapsed_time_ms) {
 634   collector_state()->set_during_marking(true);
 635   assert(!collector_state()->initiate_conc_mark_if_possible(), "we should have cleared it by now");
 636   collector_state()->set_during_initial_mark_pause(false);
 637 }
 638 
 639 void G1CollectorPolicy::record_concurrent_mark_remark_start() {
 640   _mark_remark_start_sec = os::elapsedTime();
 641   collector_state()->set_during_marking(false);
 642 }
 643 
 644 void G1CollectorPolicy::record_concurrent_mark_remark_end() {
 645   double end_time_sec = os::elapsedTime();
 646   double elapsed_time_ms = (end_time_sec - _mark_remark_start_sec)*1000.0;
 647   _analytics->report_concurrent_mark_remark_times_ms(elapsed_time_ms);
 648   _analytics->append_prev_collection_pause_end_ms(elapsed_time_ms);
 649 
 650   record_pause(Remark, _mark_remark_start_sec, end_time_sec);
 651 }
 652 
 653 void G1CollectorPolicy::record_concurrent_mark_cleanup_start() {
 654   _mark_cleanup_start_sec = os::elapsedTime();
 655 }
 656 
 657 void G1CollectorPolicy::record_concurrent_mark_cleanup_completed() {
 658   bool should_continue_with_reclaim = next_gc_should_be_mixed("request last young-only gc",
 659                                                               "skip last young-only gc");
 660   collector_state()->set_last_young_gc(should_continue_with_reclaim);
 661   // We skip the marking phase.
 662   if (!should_continue_with_reclaim) {
 663     abort_time_to_mixed_tracking();
 664   }
 665   collector_state()->set_in_marking_window(false);
 666 }
 667 
 668 double G1CollectorPolicy::average_time_ms(G1GCPhaseTimes::GCParPhases phase) const {
 669   return phase_times()->average_time_ms(phase);
 670 }
 671 
 672 double G1CollectorPolicy::young_other_time_ms() const {
 673   return phase_times()->young_cset_choice_time_ms() +
 674          phase_times()->young_free_cset_time_ms();
 675 }
 676 
 677 double G1CollectorPolicy::non_young_other_time_ms() const {
 678   return phase_times()->non_young_cset_choice_time_ms() +
 679          phase_times()->non_young_free_cset_time_ms();
 680 
 681 }
 682 
 683 double G1CollectorPolicy::other_time_ms(double pause_time_ms) const {
 684   return pause_time_ms -
 685          average_time_ms(G1GCPhaseTimes::UpdateRS) -
 686          average_time_ms(G1GCPhaseTimes::ScanRS) -
 687          average_time_ms(G1GCPhaseTimes::ObjCopy) -
 688          average_time_ms(G1GCPhaseTimes::Termination);
 689 }
 690 
 691 double G1CollectorPolicy::constant_other_time_ms(double pause_time_ms) const {
 692   return other_time_ms(pause_time_ms) - young_other_time_ms() - non_young_other_time_ms();
 693 }
 694 
 695 CollectionSetChooser* G1CollectorPolicy::cset_chooser() const {
 696   return _collection_set->cset_chooser();
 697 }
 698 
 699 bool G1CollectorPolicy::about_to_start_mixed_phase() const {
 700   return _g1->concurrent_mark()->cmThread()->during_cycle() || collector_state()->last_young_gc();
 701 }
 702 
 703 bool G1CollectorPolicy::need_to_start_conc_mark(const char* source, size_t alloc_word_size) {
 704   if (about_to_start_mixed_phase()) {
 705     return false;
 706   }
 707 
 708   size_t marking_initiating_used_threshold = _ihop_control->get_conc_mark_start_threshold();
 709 
 710   size_t cur_used_bytes = _g1->non_young_capacity_bytes();
 711   size_t alloc_byte_size = alloc_word_size * HeapWordSize;
 712   size_t marking_request_bytes = cur_used_bytes + alloc_byte_size;
 713 
 714   bool result = false;
 715   if (marking_request_bytes > marking_initiating_used_threshold) {
 716     result = collector_state()->gcs_are_young() && !collector_state()->last_young_gc();
 717     log_debug(gc, ergo, ihop)("%s occupancy: " SIZE_FORMAT "B allocation request: " SIZE_FORMAT "B threshold: " SIZE_FORMAT "B (%1.2f) source: %s",
 718                               result ? "Request concurrent cycle initiation (occupancy higher than threshold)" : "Do not request concurrent cycle initiation (still doing mixed collections)",
 719                               cur_used_bytes, alloc_byte_size, marking_initiating_used_threshold, (double) marking_initiating_used_threshold / _g1->capacity() * 100, source);
 720   }
 721 
 722   return result;
 723 }
 724 
 725 // Anything below that is considered to be zero
 726 #define MIN_TIMER_GRANULARITY 0.0000001
 727 
 728 void G1CollectorPolicy::record_collection_pause_end(double pause_time_ms, size_t cards_scanned, size_t heap_used_bytes_before_gc) {
 729   double end_time_sec = os::elapsedTime();
 730 
 731   size_t cur_used_bytes = _g1->used();
 732   assert(cur_used_bytes == _g1->recalculate_used(), "It should!");
 733   bool last_pause_included_initial_mark = false;
 734   bool update_stats = !_g1->evacuation_failed();
 735 
 736   NOT_PRODUCT(_short_lived_surv_rate_group->print());
 737 
 738   record_pause(young_gc_pause_kind(), end_time_sec - pause_time_ms / 1000.0, end_time_sec);
 739 
 740   last_pause_included_initial_mark = collector_state()->during_initial_mark_pause();
 741   if (last_pause_included_initial_mark) {
 742     record_concurrent_mark_init_end(0.0);
 743   } else {
 744     maybe_start_marking();
 745   }
 746 
 747   double app_time_ms = (phase_times()->cur_collection_start_sec() * 1000.0 - _analytics->prev_collection_pause_end_ms());
 748   if (app_time_ms < MIN_TIMER_GRANULARITY) {
 749     // This usually happens due to the timer not having the required
 750     // granularity. Some Linuxes are the usual culprits.
 751     // We'll just set it to something (arbitrarily) small.
 752     app_time_ms = 1.0;
 753   }
 754 
 755   if (update_stats) {
 756     // We maintain the invariant that all objects allocated by mutator
 757     // threads will be allocated out of eden regions. So, we can use
 758     // the eden region number allocated since the previous GC to
 759     // calculate the application's allocate rate. The only exception
 760     // to that is humongous objects that are allocated separately. But
 761     // given that humongous object allocations do not really affect
 762     // either the pause's duration nor when the next pause will take
 763     // place we can safely ignore them here.
 764     uint regions_allocated = _collection_set->eden_region_length();
 765     double alloc_rate_ms = (double) regions_allocated / app_time_ms;
 766     _analytics->report_alloc_rate_ms(alloc_rate_ms);
 767 
 768     double interval_ms =
 769       (end_time_sec - _analytics->last_known_gc_end_time_sec()) * 1000.0;
 770     _analytics->update_recent_gc_times(end_time_sec, pause_time_ms);
 771     _analytics->compute_pause_time_ratio(interval_ms, pause_time_ms);
 772   }
 773 
 774   bool new_in_marking_window = collector_state()->in_marking_window();
 775   bool new_in_marking_window_im = false;
 776   if (last_pause_included_initial_mark) {
 777     new_in_marking_window = true;
 778     new_in_marking_window_im = true;
 779   }
 780 
 781   if (collector_state()->last_young_gc()) {
 782     // This is supposed to to be the "last young GC" before we start
 783     // doing mixed GCs. Here we decide whether to start mixed GCs or not.
 784     assert(!last_pause_included_initial_mark, "The last young GC is not allowed to be an initial mark GC");
 785 
 786     if (next_gc_should_be_mixed("start mixed GCs",
 787                                 "do not start mixed GCs")) {
 788       collector_state()->set_gcs_are_young(false);
 789     } else {
 790       // We aborted the mixed GC phase early.
 791       abort_time_to_mixed_tracking();
 792     }
 793 
 794     collector_state()->set_last_young_gc(false);
 795   }
 796 
 797   if (!collector_state()->last_gc_was_young()) {
 798     // This is a mixed GC. Here we decide whether to continue doing
 799     // mixed GCs or not.
 800     if (!next_gc_should_be_mixed("continue mixed GCs",
 801                                  "do not continue mixed GCs")) {
 802       collector_state()->set_gcs_are_young(true);
 803 
 804       maybe_start_marking();
 805     }
 806   }
 807 
 808   _short_lived_surv_rate_group->start_adding_regions();
 809   // Do that for any other surv rate groups
 810 
 811   double scan_hcc_time_ms = ConcurrentG1Refine::hot_card_cache_enabled() ? average_time_ms(G1GCPhaseTimes::ScanHCC) : 0.0;
 812 
 813   if (update_stats) {
 814     double cost_per_card_ms = 0.0;
 815     if (_pending_cards > 0) {
 816       cost_per_card_ms = (average_time_ms(G1GCPhaseTimes::UpdateRS) - scan_hcc_time_ms) / (double) _pending_cards;
 817       _analytics->report_cost_per_card_ms(cost_per_card_ms);
 818     }
 819     _analytics->report_cost_scan_hcc(scan_hcc_time_ms);
 820 
 821     double cost_per_entry_ms = 0.0;
 822     if (cards_scanned > 10) {
 823       cost_per_entry_ms = average_time_ms(G1GCPhaseTimes::ScanRS) / (double) cards_scanned;
 824       _analytics->report_cost_per_entry_ms(cost_per_entry_ms, collector_state()->last_gc_was_young());
 825     }
 826 
 827     if (_max_rs_lengths > 0) {
 828       double cards_per_entry_ratio =
 829         (double) cards_scanned / (double) _max_rs_lengths;
 830       _analytics->report_cards_per_entry_ratio(cards_per_entry_ratio, collector_state()->last_gc_was_young());
 831     }
 832 
 833     // This is defensive. For a while _max_rs_lengths could get
 834     // smaller than _recorded_rs_lengths which was causing
 835     // rs_length_diff to get very large and mess up the RSet length
 836     // predictions. The reason was unsafe concurrent updates to the
 837     // _inc_cset_recorded_rs_lengths field which the code below guards
 838     // against (see CR 7118202). This bug has now been fixed (see CR
 839     // 7119027). However, I'm still worried that
 840     // _inc_cset_recorded_rs_lengths might still end up somewhat
 841     // inaccurate. The concurrent refinement thread calculates an
 842     // RSet's length concurrently with other CR threads updating it
 843     // which might cause it to calculate the length incorrectly (if,
 844     // say, it's in mid-coarsening). So I'll leave in the defensive
 845     // conditional below just in case.
 846     size_t rs_length_diff = 0;
 847     size_t recorded_rs_lengths = _collection_set->recorded_rs_lengths();
 848     if (_max_rs_lengths > recorded_rs_lengths) {
 849       rs_length_diff = _max_rs_lengths - recorded_rs_lengths;
 850     }
 851     _analytics->report_rs_length_diff((double) rs_length_diff);
 852 
 853     size_t freed_bytes = heap_used_bytes_before_gc - cur_used_bytes;
 854     size_t copied_bytes = _collection_set->bytes_used_before() - freed_bytes;
 855     double cost_per_byte_ms = 0.0;
 856 
 857     if (copied_bytes > 0) {
 858       cost_per_byte_ms = average_time_ms(G1GCPhaseTimes::ObjCopy) / (double) copied_bytes;
 859       _analytics->report_cost_per_byte_ms(cost_per_byte_ms, collector_state()->in_marking_window());
 860     }
 861 
 862     if (_collection_set->young_region_length() > 0) {
 863       _analytics->report_young_other_cost_per_region_ms(young_other_time_ms() /
 864                                                         _collection_set->young_region_length());
 865     }
 866 
 867     if (_collection_set->old_region_length() > 0) {
 868       _analytics->report_non_young_other_cost_per_region_ms(non_young_other_time_ms() /
 869                                                             _collection_set->old_region_length());
 870     }
 871 
 872     _analytics->report_constant_other_time_ms(constant_other_time_ms(pause_time_ms));
 873 
 874     _analytics->report_pending_cards((double) _pending_cards);
 875     _analytics->report_rs_lengths((double) _max_rs_lengths);
 876   }
 877 
 878   collector_state()->set_in_marking_window(new_in_marking_window);
 879   collector_state()->set_in_marking_window_im(new_in_marking_window_im);
 880   _free_regions_at_end_of_collection = _g1->num_free_regions();
 881   // IHOP control wants to know the expected young gen length if it were not
 882   // restrained by the heap reserve. Using the actual length would make the
 883   // prediction too small and the limit the young gen every time we get to the
 884   // predicted target occupancy.
 885   size_t last_unrestrained_young_length = update_young_list_max_and_target_length();
 886   update_rs_lengths_prediction();
 887 
 888   update_ihop_prediction(app_time_ms / 1000.0,
 889                          _bytes_allocated_in_old_since_last_gc,
 890                          last_unrestrained_young_length * HeapRegion::GrainBytes);
 891   _bytes_allocated_in_old_since_last_gc = 0;
 892 
 893   _ihop_control->send_trace_event(_g1->gc_tracer_stw());
 894 
 895   // Note that _mmu_tracker->max_gc_time() returns the time in seconds.
 896   double update_rs_time_goal_ms = _mmu_tracker->max_gc_time() * MILLIUNITS * G1RSetUpdatingPauseTimePercent / 100.0;
 897 
 898   if (update_rs_time_goal_ms < scan_hcc_time_ms) {
 899     log_debug(gc, ergo, refine)("Adjust concurrent refinement thresholds (scanning the HCC expected to take longer than Update RS time goal)."
 900                                 "Update RS time goal: %1.2fms Scan HCC time: %1.2fms",
 901                                 update_rs_time_goal_ms, scan_hcc_time_ms);
 902 
 903     update_rs_time_goal_ms = 0;
 904   } else {
 905     update_rs_time_goal_ms -= scan_hcc_time_ms;
 906   }
 907   adjust_concurrent_refinement(average_time_ms(G1GCPhaseTimes::UpdateRS) - scan_hcc_time_ms,
 908                                phase_times()->sum_thread_work_items(G1GCPhaseTimes::UpdateRS),
 909                                update_rs_time_goal_ms);
 910 
 911   cset_chooser()->verify();
 912 }
 913 
 914 G1IHOPControl* G1CollectorPolicy::create_ihop_control() const {
 915   if (G1UseAdaptiveIHOP) {
 916     return new G1AdaptiveIHOPControl(InitiatingHeapOccupancyPercent,
 917                                      &_predictor,
 918                                      G1ReservePercent,
 919                                      G1HeapWastePercent);
 920   } else {
 921     return new G1StaticIHOPControl(InitiatingHeapOccupancyPercent);
 922   }
 923 }
 924 
 925 void G1CollectorPolicy::update_ihop_prediction(double mutator_time_s,
 926                                                size_t mutator_alloc_bytes,
 927                                                size_t young_gen_size) {
 928   // Always try to update IHOP prediction. Even evacuation failures give information
 929   // about e.g. whether to start IHOP earlier next time.
 930 
 931   // Avoid using really small application times that might create samples with
 932   // very high or very low values. They may be caused by e.g. back-to-back gcs.
 933   double const min_valid_time = 1e-6;
 934 
 935   bool report = false;
 936 
 937   double marking_to_mixed_time = -1.0;
 938   if (!collector_state()->last_gc_was_young() && _initial_mark_to_mixed.has_result()) {
 939     marking_to_mixed_time = _initial_mark_to_mixed.last_marking_time();
 940     assert(marking_to_mixed_time > 0.0,
 941            "Initial mark to mixed time must be larger than zero but is %.3f",
 942            marking_to_mixed_time);
 943     if (marking_to_mixed_time > min_valid_time) {
 944       _ihop_control->update_marking_length(marking_to_mixed_time);
 945       report = true;
 946     }
 947   }
 948 
 949   // As an approximation for the young gc promotion rates during marking we use
 950   // all of them. In many applications there are only a few if any young gcs during
 951   // marking, which makes any prediction useless. This increases the accuracy of the
 952   // prediction.
 953   if (collector_state()->last_gc_was_young() && mutator_time_s > min_valid_time) {
 954     _ihop_control->update_allocation_info(mutator_time_s, mutator_alloc_bytes, young_gen_size);
 955     report = true;
 956   }
 957 
 958   if (report) {
 959     report_ihop_statistics();
 960   }
 961 }
 962 
 963 void G1CollectorPolicy::report_ihop_statistics() {
 964   _ihop_control->print();
 965 }
 966 
 967 void G1CollectorPolicy::print_phases() {
 968   phase_times()->print();
 969 }
 970 
 971 void G1CollectorPolicy::adjust_concurrent_refinement(double update_rs_time,
 972                                                      double update_rs_processed_buffers,
 973                                                      double goal_ms) {
 974   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
 975   ConcurrentG1Refine *cg1r = G1CollectedHeap::heap()->concurrent_g1_refine();
 976 
 977   if (G1UseAdaptiveConcRefinement) {
 978     const int k_gy = 3, k_gr = 6;
 979     const double inc_k = 1.1, dec_k = 0.9;
 980 
 981     size_t g = cg1r->green_zone();
 982     if (update_rs_time > goal_ms) {
 983       g = (size_t)(g * dec_k);  // Can become 0, that's OK. That would mean a mutator-only processing.
 984     } else {
 985       if (update_rs_time < goal_ms && update_rs_processed_buffers > g) {
 986         g = (size_t)MAX2(g * inc_k, g + 1.0);
 987       }
 988     }
 989     // Change the refinement threads params
 990     cg1r->set_green_zone(g);
 991     cg1r->set_yellow_zone(g * k_gy);
 992     cg1r->set_red_zone(g * k_gr);
 993     cg1r->reinitialize_threads();
 994 
 995     size_t processing_threshold_delta = MAX2<size_t>(cg1r->green_zone() * _predictor.sigma(), 1);
 996     size_t processing_threshold = MIN2(cg1r->green_zone() + processing_threshold_delta,
 997                                     cg1r->yellow_zone());
 998     // Change the barrier params
 999     dcqs.set_process_completed_threshold((int)processing_threshold);
1000     dcqs.set_max_completed_queue((int)cg1r->red_zone());
1001   }
1002 
1003   size_t curr_queue_size = dcqs.completed_buffers_num();
1004   if (curr_queue_size >= cg1r->yellow_zone()) {
1005     dcqs.set_completed_queue_padding(curr_queue_size);
1006   } else {
1007     dcqs.set_completed_queue_padding(0);
1008   }
1009   dcqs.notify_if_necessary();
1010 }
1011 
1012 double G1CollectorPolicy::predict_yg_surv_rate(int age, SurvRateGroup* surv_rate_group) const {
1013   TruncatedSeq* seq = surv_rate_group->get_seq(age);
1014   guarantee(seq->num() > 0, "There should be some young gen survivor samples available. Tried to access with age %d", age);
1015   double pred = _predictor.get_new_prediction(seq);
1016   if (pred > 1.0) {
1017     pred = 1.0;
1018   }
1019   return pred;
1020 }
1021 
1022 double G1CollectorPolicy::predict_yg_surv_rate(int age) const {
1023   return predict_yg_surv_rate(age, _short_lived_surv_rate_group);
1024 }
1025 
1026 double G1CollectorPolicy::accum_yg_surv_rate_pred(int age) const {
1027   return _short_lived_surv_rate_group->accum_surv_rate_pred(age);
1028 }
1029 
1030 double G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
1031                                                        size_t scanned_cards) const {
1032   return
1033     _analytics->predict_rs_update_time_ms(pending_cards) +
1034     _analytics->predict_rs_scan_time_ms(scanned_cards, collector_state()->gcs_are_young()) +
1035     _analytics->predict_constant_other_time_ms();
1036 }
1037 
1038 double G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) const {
1039   size_t rs_length = _analytics->predict_rs_lengths() + _analytics->predict_rs_length_diff();
1040   size_t card_num = _analytics->predict_card_num(rs_length, collector_state()->gcs_are_young());
1041   return predict_base_elapsed_time_ms(pending_cards, card_num);
1042 }
1043 
1044 size_t G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) const {
1045   size_t bytes_to_copy;
1046   if (hr->is_marked())
1047     bytes_to_copy = hr->max_live_bytes();
1048   else {
1049     assert(hr->is_young() && hr->age_in_surv_rate_group() != -1, "invariant");
1050     int age = hr->age_in_surv_rate_group();
1051     double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
1052     bytes_to_copy = (size_t) (hr->used() * yg_surv_rate);
1053   }
1054   return bytes_to_copy;
1055 }
1056 
1057 double G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
1058                                                          bool for_young_gc) const {
1059   size_t rs_length = hr->rem_set()->occupied();
1060   // Predicting the number of cards is based on which type of GC
1061   // we're predicting for.
1062   size_t card_num = _analytics->predict_card_num(rs_length, for_young_gc);
1063   size_t bytes_to_copy = predict_bytes_to_copy(hr);
1064 
1065   double region_elapsed_time_ms =
1066     _analytics->predict_rs_scan_time_ms(card_num, collector_state()->gcs_are_young()) +
1067     _analytics->predict_object_copy_time_ms(bytes_to_copy, collector_state()->during_concurrent_mark());
1068 
1069   // The prediction of the "other" time for this region is based
1070   // upon the region type and NOT the GC type.
1071   if (hr->is_young()) {
1072     region_elapsed_time_ms += _analytics->predict_young_other_time_ms(1);
1073   } else {
1074     region_elapsed_time_ms += _analytics->predict_non_young_other_time_ms(1);
1075   }
1076   return region_elapsed_time_ms;
1077 }
1078 
1079 
1080 void G1CollectorPolicy::print_yg_surv_rate_info() const {
1081 #ifndef PRODUCT
1082   _short_lived_surv_rate_group->print_surv_rate_summary();
1083   // add this call for any other surv rate groups
1084 #endif // PRODUCT
1085 }
1086 
1087 bool G1CollectorPolicy::is_young_list_full() const {
1088   uint young_list_length = _g1->young_list()->length();
1089   uint young_list_target_length = _young_list_target_length;
1090   return young_list_length >= young_list_target_length;
1091 }
1092 
1093 bool G1CollectorPolicy::can_expand_young_list() const {
1094   uint young_list_length = _g1->young_list()->length();
1095   uint young_list_max_length = _young_list_max_length;
1096   return young_list_length < young_list_max_length;
1097 }
1098 
1099 bool G1CollectorPolicy::adaptive_young_list_length() const {
1100   return _young_gen_sizer->adaptive_young_list_length();
1101 }
1102 
1103 void G1CollectorPolicy::update_max_gc_locker_expansion() {
1104   uint expansion_region_num = 0;
1105   if (GCLockerEdenExpansionPercent > 0) {
1106     double perc = (double) GCLockerEdenExpansionPercent / 100.0;
1107     double expansion_region_num_d = perc * (double) _young_list_target_length;
1108     // We use ceiling so that if expansion_region_num_d is > 0.0 (but
1109     // less than 1.0) we'll get 1.
1110     expansion_region_num = (uint) ceil(expansion_region_num_d);
1111   } else {
1112     assert(expansion_region_num == 0, "sanity");
1113   }
1114   _young_list_max_length = _young_list_target_length + expansion_region_num;
1115   assert(_young_list_target_length <= _young_list_max_length, "post-condition");
1116 }
1117 
1118 // Calculates survivor space parameters.
1119 void G1CollectorPolicy::update_survivors_policy() {
1120   double max_survivor_regions_d =
1121                  (double) _young_list_target_length / (double) SurvivorRatio;
1122   // We use ceiling so that if max_survivor_regions_d is > 0.0 (but
1123   // smaller than 1.0) we'll get 1.
1124   _max_survivor_regions = (uint) ceil(max_survivor_regions_d);
1125 
1126   _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
1127         HeapRegion::GrainWords * _max_survivor_regions, counters());
1128 }
1129 
1130 bool G1CollectorPolicy::force_initial_mark_if_outside_cycle(GCCause::Cause gc_cause) {
1131   // We actually check whether we are marking here and not if we are in a
1132   // reclamation phase. This means that we will schedule a concurrent mark
1133   // even while we are still in the process of reclaiming memory.
1134   bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();
1135   if (!during_cycle) {
1136     log_debug(gc, ergo)("Request concurrent cycle initiation (requested by GC cause). GC cause: %s", GCCause::to_string(gc_cause));
1137     collector_state()->set_initiate_conc_mark_if_possible(true);
1138     return true;
1139   } else {
1140     log_debug(gc, ergo)("Do not request concurrent cycle initiation (concurrent cycle already in progress). GC cause: %s", GCCause::to_string(gc_cause));
1141     return false;
1142   }
1143 }
1144 
1145 void G1CollectorPolicy::initiate_conc_mark() {
1146   collector_state()->set_during_initial_mark_pause(true);
1147   collector_state()->set_initiate_conc_mark_if_possible(false);
1148 }
1149 
1150 void G1CollectorPolicy::decide_on_conc_mark_initiation() {
1151   // We are about to decide on whether this pause will be an
1152   // initial-mark pause.
1153 
1154   // First, collector_state()->during_initial_mark_pause() should not be already set. We
1155   // will set it here if we have to. However, it should be cleared by
1156   // the end of the pause (it's only set for the duration of an
1157   // initial-mark pause).
1158   assert(!collector_state()->during_initial_mark_pause(), "pre-condition");
1159 
1160   if (collector_state()->initiate_conc_mark_if_possible()) {
1161     // We had noticed on a previous pause that the heap occupancy has
1162     // gone over the initiating threshold and we should start a
1163     // concurrent marking cycle. So we might initiate one.
1164 
1165     if (!about_to_start_mixed_phase() && collector_state()->gcs_are_young()) {
1166       // Initiate a new initial mark if there is no marking or reclamation going on.
1167       initiate_conc_mark();
1168       log_debug(gc, ergo)("Initiate concurrent cycle (concurrent cycle initiation requested)");
1169     } else if (_g1->is_user_requested_concurrent_full_gc(_g1->gc_cause())) {
1170       // Initiate a user requested initial mark. An initial mark must be young only
1171       // GC, so the collector state must be updated to reflect this.
1172       collector_state()->set_gcs_are_young(true);
1173       collector_state()->set_last_young_gc(false);
1174 
1175       abort_time_to_mixed_tracking();
1176       initiate_conc_mark();
1177       log_debug(gc, ergo)("Initiate concurrent cycle (user requested concurrent cycle)");
1178     } else {
1179       // The concurrent marking thread is still finishing up the
1180       // previous cycle. If we start one right now the two cycles
1181       // overlap. In particular, the concurrent marking thread might
1182       // be in the process of clearing the next marking bitmap (which
1183       // we will use for the next cycle if we start one). Starting a
1184       // cycle now will be bad given that parts of the marking
1185       // information might get cleared by the marking thread. And we
1186       // cannot wait for the marking thread to finish the cycle as it
1187       // periodically yields while clearing the next marking bitmap
1188       // and, if it's in a yield point, it's waiting for us to
1189       // finish. So, at this point we will not start a cycle and we'll
1190       // let the concurrent marking thread complete the last one.
1191       log_debug(gc, ergo)("Do not initiate concurrent cycle (concurrent cycle already in progress)");
1192     }
1193   }
1194 }
1195 
1196 void G1CollectorPolicy::record_concurrent_mark_cleanup_end() {
1197   cset_chooser()->rebuild(_g1->workers(), _g1->num_regions());
1198 
1199   double end_sec = os::elapsedTime();
1200   double elapsed_time_ms = (end_sec - _mark_cleanup_start_sec) * 1000.0;
1201   _analytics->report_concurrent_mark_cleanup_times_ms(elapsed_time_ms);
1202   _analytics->append_prev_collection_pause_end_ms(elapsed_time_ms);
1203 
1204   record_pause(Cleanup, _mark_cleanup_start_sec, end_sec);
1205 }
1206 
1207 double G1CollectorPolicy::reclaimable_bytes_perc(size_t reclaimable_bytes) const {
1208   // Returns the given amount of reclaimable bytes (that represents
1209   // the amount of reclaimable space still to be collected) as a
1210   // percentage of the current heap capacity.
1211   size_t capacity_bytes = _g1->capacity();
1212   return (double) reclaimable_bytes * 100.0 / (double) capacity_bytes;
1213 }
1214 
1215 void G1CollectorPolicy::maybe_start_marking() {
1216   if (need_to_start_conc_mark("end of GC")) {
1217     // Note: this might have already been set, if during the last
1218     // pause we decided to start a cycle but at the beginning of
1219     // this pause we decided to postpone it. That's OK.
1220     collector_state()->set_initiate_conc_mark_if_possible(true);
1221   }
1222 }
1223 
1224 G1CollectorPolicy::PauseKind G1CollectorPolicy::young_gc_pause_kind() const {
1225   assert(!collector_state()->full_collection(), "must be");
1226   if (collector_state()->during_initial_mark_pause()) {
1227     assert(collector_state()->last_gc_was_young(), "must be");
1228     assert(!collector_state()->last_young_gc(), "must be");
1229     return InitialMarkGC;
1230   } else if (collector_state()->last_young_gc()) {
1231     assert(!collector_state()->during_initial_mark_pause(), "must be");
1232     assert(collector_state()->last_gc_was_young(), "must be");
1233     return LastYoungGC;
1234   } else if (!collector_state()->last_gc_was_young()) {
1235     assert(!collector_state()->during_initial_mark_pause(), "must be");
1236     assert(!collector_state()->last_young_gc(), "must be");
1237     return MixedGC;
1238   } else {
1239     assert(collector_state()->last_gc_was_young(), "must be");
1240     assert(!collector_state()->during_initial_mark_pause(), "must be");
1241     assert(!collector_state()->last_young_gc(), "must be");
1242     return YoungOnlyGC;
1243   }
1244 }
1245 
1246 void G1CollectorPolicy::record_pause(PauseKind kind, double start, double end) {
1247   // Manage the MMU tracker. For some reason it ignores Full GCs.
1248   if (kind != FullGC) {
1249     _mmu_tracker->add_pause(start, end);
1250   }
1251   // Manage the mutator time tracking from initial mark to first mixed gc.
1252   switch (kind) {
1253     case FullGC:
1254       abort_time_to_mixed_tracking();
1255       break;
1256     case Cleanup:
1257     case Remark:
1258     case YoungOnlyGC:
1259     case LastYoungGC:
1260       _initial_mark_to_mixed.add_pause(end - start);
1261       break;
1262     case InitialMarkGC:
1263       _initial_mark_to_mixed.record_initial_mark_end(end);
1264       break;
1265     case MixedGC:
1266       _initial_mark_to_mixed.record_mixed_gc_start(start);
1267       break;
1268     default:
1269       ShouldNotReachHere();
1270   }
1271 }
1272 
1273 void G1CollectorPolicy::abort_time_to_mixed_tracking() {
1274   _initial_mark_to_mixed.reset();
1275 }
1276 
1277 bool G1CollectorPolicy::next_gc_should_be_mixed(const char* true_action_str,
1278                                                 const char* false_action_str) const {
1279   if (cset_chooser()->is_empty()) {
1280     log_debug(gc, ergo)("%s (candidate old regions not available)", false_action_str);
1281     return false;
1282   }
1283 
1284   // Is the amount of uncollected reclaimable space above G1HeapWastePercent?
1285   size_t reclaimable_bytes = cset_chooser()->remaining_reclaimable_bytes();
1286   double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);
1287   double threshold = (double) G1HeapWastePercent;
1288   if (reclaimable_perc <= threshold) {
1289     log_debug(gc, ergo)("%s (reclaimable percentage not over threshold). candidate old regions: %u reclaimable: " SIZE_FORMAT " (%1.2f) threshold: " UINTX_FORMAT,
1290                         false_action_str, cset_chooser()->remaining_regions(), reclaimable_bytes, reclaimable_perc, G1HeapWastePercent);
1291     return false;
1292   }
1293   log_debug(gc, ergo)("%s (candidate old regions available). candidate old regions: %u reclaimable: " SIZE_FORMAT " (%1.2f) threshold: " UINTX_FORMAT,
1294                       true_action_str, cset_chooser()->remaining_regions(), reclaimable_bytes, reclaimable_perc, G1HeapWastePercent);
1295   return true;
1296 }
1297 
1298 uint G1CollectorPolicy::calc_min_old_cset_length() const {
1299   // The min old CSet region bound is based on the maximum desired
1300   // number of mixed GCs after a cycle. I.e., even if some old regions
1301   // look expensive, we should add them to the CSet anyway to make
1302   // sure we go through the available old regions in no more than the
1303   // maximum desired number of mixed GCs.
1304   //
1305   // The calculation is based on the number of marked regions we added
1306   // to the CSet chooser in the first place, not how many remain, so
1307   // that the result is the same during all mixed GCs that follow a cycle.
1308 
1309   const size_t region_num = (size_t) cset_chooser()->length();
1310   const size_t gc_num = (size_t) MAX2(G1MixedGCCountTarget, (uintx) 1);
1311   size_t result = region_num / gc_num;
1312   // emulate ceiling
1313   if (result * gc_num < region_num) {
1314     result += 1;
1315   }
1316   return (uint) result;
1317 }
1318 
1319 uint G1CollectorPolicy::calc_max_old_cset_length() const {
1320   // The max old CSet region bound is based on the threshold expressed
1321   // as a percentage of the heap size. I.e., it should bound the
1322   // number of old regions added to the CSet irrespective of how many
1323   // of them are available.
1324 
1325   const G1CollectedHeap* g1h = G1CollectedHeap::heap();
1326   const size_t region_num = g1h->num_regions();
1327   const size_t perc = (size_t) G1OldCSetRegionThresholdPercent;
1328   size_t result = region_num * perc / 100;
1329   // emulate ceiling
1330   if (100 * result < region_num * perc) {
1331     result += 1;
1332   }
1333   return (uint) result;
1334 }
1335 
1336 void G1CollectorPolicy::finalize_collection_set(double target_pause_time_ms) {
1337   double time_remaining_ms = _collection_set->finalize_young_part(target_pause_time_ms);
1338   _collection_set->finalize_old_part(time_remaining_ms);
1339 }