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   _g1->concurrent_g1_refine()->adjust(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 double G1CollectorPolicy::predict_yg_surv_rate(int age, SurvRateGroup* surv_rate_group) const {
 972   TruncatedSeq* seq = surv_rate_group->get_seq(age);
 973   guarantee(seq->num() > 0, "There should be some young gen survivor samples available. Tried to access with age %d", age);
 974   double pred = _predictor.get_new_prediction(seq);
 975   if (pred > 1.0) {
 976     pred = 1.0;
 977   }
 978   return pred;
 979 }
 980 
 981 double G1CollectorPolicy::predict_yg_surv_rate(int age) const {
 982   return predict_yg_surv_rate(age, _short_lived_surv_rate_group);
 983 }
 984 
 985 double G1CollectorPolicy::accum_yg_surv_rate_pred(int age) const {
 986   return _short_lived_surv_rate_group->accum_surv_rate_pred(age);
 987 }
 988 
 989 double G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards,
 990                                                        size_t scanned_cards) const {
 991   return
 992     _analytics->predict_rs_update_time_ms(pending_cards) +
 993     _analytics->predict_rs_scan_time_ms(scanned_cards, collector_state()->gcs_are_young()) +
 994     _analytics->predict_constant_other_time_ms();
 995 }
 996 
 997 double G1CollectorPolicy::predict_base_elapsed_time_ms(size_t pending_cards) const {
 998   size_t rs_length = _analytics->predict_rs_lengths() + _analytics->predict_rs_length_diff();
 999   size_t card_num = _analytics->predict_card_num(rs_length, collector_state()->gcs_are_young());
1000   return predict_base_elapsed_time_ms(pending_cards, card_num);
1001 }
1002 
1003 size_t G1CollectorPolicy::predict_bytes_to_copy(HeapRegion* hr) const {
1004   size_t bytes_to_copy;
1005   if (hr->is_marked())
1006     bytes_to_copy = hr->max_live_bytes();
1007   else {
1008     assert(hr->is_young() && hr->age_in_surv_rate_group() != -1, "invariant");
1009     int age = hr->age_in_surv_rate_group();
1010     double yg_surv_rate = predict_yg_surv_rate(age, hr->surv_rate_group());
1011     bytes_to_copy = (size_t) (hr->used() * yg_surv_rate);
1012   }
1013   return bytes_to_copy;
1014 }
1015 
1016 double G1CollectorPolicy::predict_region_elapsed_time_ms(HeapRegion* hr,
1017                                                          bool for_young_gc) const {
1018   size_t rs_length = hr->rem_set()->occupied();
1019   // Predicting the number of cards is based on which type of GC
1020   // we're predicting for.
1021   size_t card_num = _analytics->predict_card_num(rs_length, for_young_gc);
1022   size_t bytes_to_copy = predict_bytes_to_copy(hr);
1023 
1024   double region_elapsed_time_ms =
1025     _analytics->predict_rs_scan_time_ms(card_num, collector_state()->gcs_are_young()) +
1026     _analytics->predict_object_copy_time_ms(bytes_to_copy, collector_state()->during_concurrent_mark());
1027 
1028   // The prediction of the "other" time for this region is based
1029   // upon the region type and NOT the GC type.
1030   if (hr->is_young()) {
1031     region_elapsed_time_ms += _analytics->predict_young_other_time_ms(1);
1032   } else {
1033     region_elapsed_time_ms += _analytics->predict_non_young_other_time_ms(1);
1034   }
1035   return region_elapsed_time_ms;
1036 }
1037 
1038 
1039 void G1CollectorPolicy::print_yg_surv_rate_info() const {
1040 #ifndef PRODUCT
1041   _short_lived_surv_rate_group->print_surv_rate_summary();
1042   // add this call for any other surv rate groups
1043 #endif // PRODUCT
1044 }
1045 
1046 bool G1CollectorPolicy::is_young_list_full() const {
1047   uint young_list_length = _g1->young_list()->length();
1048   uint young_list_target_length = _young_list_target_length;
1049   return young_list_length >= young_list_target_length;
1050 }
1051 
1052 bool G1CollectorPolicy::can_expand_young_list() const {
1053   uint young_list_length = _g1->young_list()->length();
1054   uint young_list_max_length = _young_list_max_length;
1055   return young_list_length < young_list_max_length;
1056 }
1057 
1058 bool G1CollectorPolicy::adaptive_young_list_length() const {
1059   return _young_gen_sizer->adaptive_young_list_length();
1060 }
1061 
1062 void G1CollectorPolicy::update_max_gc_locker_expansion() {
1063   uint expansion_region_num = 0;
1064   if (GCLockerEdenExpansionPercent > 0) {
1065     double perc = (double) GCLockerEdenExpansionPercent / 100.0;
1066     double expansion_region_num_d = perc * (double) _young_list_target_length;
1067     // We use ceiling so that if expansion_region_num_d is > 0.0 (but
1068     // less than 1.0) we'll get 1.
1069     expansion_region_num = (uint) ceil(expansion_region_num_d);
1070   } else {
1071     assert(expansion_region_num == 0, "sanity");
1072   }
1073   _young_list_max_length = _young_list_target_length + expansion_region_num;
1074   assert(_young_list_target_length <= _young_list_max_length, "post-condition");
1075 }
1076 
1077 // Calculates survivor space parameters.
1078 void G1CollectorPolicy::update_survivors_policy() {
1079   double max_survivor_regions_d =
1080                  (double) _young_list_target_length / (double) SurvivorRatio;
1081   // We use ceiling so that if max_survivor_regions_d is > 0.0 (but
1082   // smaller than 1.0) we'll get 1.
1083   _max_survivor_regions = (uint) ceil(max_survivor_regions_d);
1084 
1085   _tenuring_threshold = _survivors_age_table.compute_tenuring_threshold(
1086         HeapRegion::GrainWords * _max_survivor_regions, counters());
1087 }
1088 
1089 bool G1CollectorPolicy::force_initial_mark_if_outside_cycle(GCCause::Cause gc_cause) {
1090   // We actually check whether we are marking here and not if we are in a
1091   // reclamation phase. This means that we will schedule a concurrent mark
1092   // even while we are still in the process of reclaiming memory.
1093   bool during_cycle = _g1->concurrent_mark()->cmThread()->during_cycle();
1094   if (!during_cycle) {
1095     log_debug(gc, ergo)("Request concurrent cycle initiation (requested by GC cause). GC cause: %s", GCCause::to_string(gc_cause));
1096     collector_state()->set_initiate_conc_mark_if_possible(true);
1097     return true;
1098   } else {
1099     log_debug(gc, ergo)("Do not request concurrent cycle initiation (concurrent cycle already in progress). GC cause: %s", GCCause::to_string(gc_cause));
1100     return false;
1101   }
1102 }
1103 
1104 void G1CollectorPolicy::initiate_conc_mark() {
1105   collector_state()->set_during_initial_mark_pause(true);
1106   collector_state()->set_initiate_conc_mark_if_possible(false);
1107 }
1108 
1109 void G1CollectorPolicy::decide_on_conc_mark_initiation() {
1110   // We are about to decide on whether this pause will be an
1111   // initial-mark pause.
1112 
1113   // First, collector_state()->during_initial_mark_pause() should not be already set. We
1114   // will set it here if we have to. However, it should be cleared by
1115   // the end of the pause (it's only set for the duration of an
1116   // initial-mark pause).
1117   assert(!collector_state()->during_initial_mark_pause(), "pre-condition");
1118 
1119   if (collector_state()->initiate_conc_mark_if_possible()) {
1120     // We had noticed on a previous pause that the heap occupancy has
1121     // gone over the initiating threshold and we should start a
1122     // concurrent marking cycle. So we might initiate one.
1123 
1124     if (!about_to_start_mixed_phase() && collector_state()->gcs_are_young()) {
1125       // Initiate a new initial mark if there is no marking or reclamation going on.
1126       initiate_conc_mark();
1127       log_debug(gc, ergo)("Initiate concurrent cycle (concurrent cycle initiation requested)");
1128     } else if (_g1->is_user_requested_concurrent_full_gc(_g1->gc_cause())) {
1129       // Initiate a user requested initial mark. An initial mark must be young only
1130       // GC, so the collector state must be updated to reflect this.
1131       collector_state()->set_gcs_are_young(true);
1132       collector_state()->set_last_young_gc(false);
1133 
1134       abort_time_to_mixed_tracking();
1135       initiate_conc_mark();
1136       log_debug(gc, ergo)("Initiate concurrent cycle (user requested concurrent cycle)");
1137     } else {
1138       // The concurrent marking thread is still finishing up the
1139       // previous cycle. If we start one right now the two cycles
1140       // overlap. In particular, the concurrent marking thread might
1141       // be in the process of clearing the next marking bitmap (which
1142       // we will use for the next cycle if we start one). Starting a
1143       // cycle now will be bad given that parts of the marking
1144       // information might get cleared by the marking thread. And we
1145       // cannot wait for the marking thread to finish the cycle as it
1146       // periodically yields while clearing the next marking bitmap
1147       // and, if it's in a yield point, it's waiting for us to
1148       // finish. So, at this point we will not start a cycle and we'll
1149       // let the concurrent marking thread complete the last one.
1150       log_debug(gc, ergo)("Do not initiate concurrent cycle (concurrent cycle already in progress)");
1151     }
1152   }
1153 }
1154 
1155 void G1CollectorPolicy::record_concurrent_mark_cleanup_end() {
1156   cset_chooser()->rebuild(_g1->workers(), _g1->num_regions());
1157 
1158   double end_sec = os::elapsedTime();
1159   double elapsed_time_ms = (end_sec - _mark_cleanup_start_sec) * 1000.0;
1160   _analytics->report_concurrent_mark_cleanup_times_ms(elapsed_time_ms);
1161   _analytics->append_prev_collection_pause_end_ms(elapsed_time_ms);
1162 
1163   record_pause(Cleanup, _mark_cleanup_start_sec, end_sec);
1164 }
1165 
1166 double G1CollectorPolicy::reclaimable_bytes_perc(size_t reclaimable_bytes) const {
1167   // Returns the given amount of reclaimable bytes (that represents
1168   // the amount of reclaimable space still to be collected) as a
1169   // percentage of the current heap capacity.
1170   size_t capacity_bytes = _g1->capacity();
1171   return (double) reclaimable_bytes * 100.0 / (double) capacity_bytes;
1172 }
1173 
1174 void G1CollectorPolicy::maybe_start_marking() {
1175   if (need_to_start_conc_mark("end of GC")) {
1176     // Note: this might have already been set, if during the last
1177     // pause we decided to start a cycle but at the beginning of
1178     // this pause we decided to postpone it. That's OK.
1179     collector_state()->set_initiate_conc_mark_if_possible(true);
1180   }
1181 }
1182 
1183 G1CollectorPolicy::PauseKind G1CollectorPolicy::young_gc_pause_kind() const {
1184   assert(!collector_state()->full_collection(), "must be");
1185   if (collector_state()->during_initial_mark_pause()) {
1186     assert(collector_state()->last_gc_was_young(), "must be");
1187     assert(!collector_state()->last_young_gc(), "must be");
1188     return InitialMarkGC;
1189   } else if (collector_state()->last_young_gc()) {
1190     assert(!collector_state()->during_initial_mark_pause(), "must be");
1191     assert(collector_state()->last_gc_was_young(), "must be");
1192     return LastYoungGC;
1193   } else if (!collector_state()->last_gc_was_young()) {
1194     assert(!collector_state()->during_initial_mark_pause(), "must be");
1195     assert(!collector_state()->last_young_gc(), "must be");
1196     return MixedGC;
1197   } else {
1198     assert(collector_state()->last_gc_was_young(), "must be");
1199     assert(!collector_state()->during_initial_mark_pause(), "must be");
1200     assert(!collector_state()->last_young_gc(), "must be");
1201     return YoungOnlyGC;
1202   }
1203 }
1204 
1205 void G1CollectorPolicy::record_pause(PauseKind kind, double start, double end) {
1206   // Manage the MMU tracker. For some reason it ignores Full GCs.
1207   if (kind != FullGC) {
1208     _mmu_tracker->add_pause(start, end);
1209   }
1210   // Manage the mutator time tracking from initial mark to first mixed gc.
1211   switch (kind) {
1212     case FullGC:
1213       abort_time_to_mixed_tracking();
1214       break;
1215     case Cleanup:
1216     case Remark:
1217     case YoungOnlyGC:
1218     case LastYoungGC:
1219       _initial_mark_to_mixed.add_pause(end - start);
1220       break;
1221     case InitialMarkGC:
1222       _initial_mark_to_mixed.record_initial_mark_end(end);
1223       break;
1224     case MixedGC:
1225       _initial_mark_to_mixed.record_mixed_gc_start(start);
1226       break;
1227     default:
1228       ShouldNotReachHere();
1229   }
1230 }
1231 
1232 void G1CollectorPolicy::abort_time_to_mixed_tracking() {
1233   _initial_mark_to_mixed.reset();
1234 }
1235 
1236 bool G1CollectorPolicy::next_gc_should_be_mixed(const char* true_action_str,
1237                                                 const char* false_action_str) const {
1238   if (cset_chooser()->is_empty()) {
1239     log_debug(gc, ergo)("%s (candidate old regions not available)", false_action_str);
1240     return false;
1241   }
1242 
1243   // Is the amount of uncollected reclaimable space above G1HeapWastePercent?
1244   size_t reclaimable_bytes = cset_chooser()->remaining_reclaimable_bytes();
1245   double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);
1246   double threshold = (double) G1HeapWastePercent;
1247   if (reclaimable_perc <= threshold) {
1248     log_debug(gc, ergo)("%s (reclaimable percentage not over threshold). candidate old regions: %u reclaimable: " SIZE_FORMAT " (%1.2f) threshold: " UINTX_FORMAT,
1249                         false_action_str, cset_chooser()->remaining_regions(), reclaimable_bytes, reclaimable_perc, G1HeapWastePercent);
1250     return false;
1251   }
1252   log_debug(gc, ergo)("%s (candidate old regions available). candidate old regions: %u reclaimable: " SIZE_FORMAT " (%1.2f) threshold: " UINTX_FORMAT,
1253                       true_action_str, cset_chooser()->remaining_regions(), reclaimable_bytes, reclaimable_perc, G1HeapWastePercent);
1254   return true;
1255 }
1256 
1257 uint G1CollectorPolicy::calc_min_old_cset_length() const {
1258   // The min old CSet region bound is based on the maximum desired
1259   // number of mixed GCs after a cycle. I.e., even if some old regions
1260   // look expensive, we should add them to the CSet anyway to make
1261   // sure we go through the available old regions in no more than the
1262   // maximum desired number of mixed GCs.
1263   //
1264   // The calculation is based on the number of marked regions we added
1265   // to the CSet chooser in the first place, not how many remain, so
1266   // that the result is the same during all mixed GCs that follow a cycle.
1267 
1268   const size_t region_num = (size_t) cset_chooser()->length();
1269   const size_t gc_num = (size_t) MAX2(G1MixedGCCountTarget, (uintx) 1);
1270   size_t result = region_num / gc_num;
1271   // emulate ceiling
1272   if (result * gc_num < region_num) {
1273     result += 1;
1274   }
1275   return (uint) result;
1276 }
1277 
1278 uint G1CollectorPolicy::calc_max_old_cset_length() const {
1279   // The max old CSet region bound is based on the threshold expressed
1280   // as a percentage of the heap size. I.e., it should bound the
1281   // number of old regions added to the CSet irrespective of how many
1282   // of them are available.
1283 
1284   const G1CollectedHeap* g1h = G1CollectedHeap::heap();
1285   const size_t region_num = g1h->num_regions();
1286   const size_t perc = (size_t) G1OldCSetRegionThresholdPercent;
1287   size_t result = region_num * perc / 100;
1288   // emulate ceiling
1289   if (100 * result < region_num * perc) {
1290     result += 1;
1291   }
1292   return (uint) result;
1293 }
1294 
1295 void G1CollectorPolicy::finalize_collection_set(double target_pause_time_ms) {
1296   double time_remaining_ms = _collection_set->finalize_young_part(target_pause_time_ms);
1297   _collection_set->finalize_old_part(time_remaining_ms);
1298 }