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