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