1 /*
   2  * Copyright (c) 2004, 2018, 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/shared/adaptiveSizePolicy.hpp"
  27 #include "gc/shared/gcCause.hpp"
  28 #include "gc/shared/gcUtil.inline.hpp"
  29 #include "logging/log.hpp"
  30 #include "runtime/timer.hpp"
  31 
  32 elapsedTimer AdaptiveSizePolicy::_minor_timer;
  33 elapsedTimer AdaptiveSizePolicy::_major_timer;
  34 
  35 // The throughput goal is implemented as
  36 //      _throughput_goal = 1 - ( 1 / (1 + gc_cost_ratio))
  37 // gc_cost_ratio is the ratio
  38 //      application cost / gc cost
  39 // For example a gc_cost_ratio of 4 translates into a
  40 // throughput goal of .80
  41 
  42 AdaptiveSizePolicy::AdaptiveSizePolicy(size_t init_eden_size,
  43                                        size_t init_promo_size,
  44                                        size_t init_survivor_size,
  45                                        double gc_pause_goal_sec,
  46                                        uint gc_cost_ratio) :
  47     _throughput_goal(1.0 - double(1.0 / (1.0 + (double) gc_cost_ratio))),
  48     _eden_size(init_eden_size),
  49     _promo_size(init_promo_size),
  50     _survivor_size(init_survivor_size),
  51     _latest_minor_mutator_interval_seconds(0),
  52     _threshold_tolerance_percent(1.0 + ThresholdTolerance/100.0),
  53     _gc_pause_goal_sec(gc_pause_goal_sec),
  54     _young_gen_change_for_minor_throughput(0),
  55     _old_gen_change_for_major_throughput(0) {
  56   assert(AdaptiveSizePolicyGCTimeLimitThreshold > 0,
  57     "No opportunity to clear SoftReferences before GC overhead limit");
  58   _avg_minor_pause    =
  59     new AdaptivePaddedAverage(AdaptiveTimeWeight, PausePadding);
  60   _avg_minor_interval = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
  61   _avg_minor_gc_cost  = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
  62   _avg_major_gc_cost  = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
  63 
  64   _avg_young_live     = new AdaptiveWeightedAverage(AdaptiveSizePolicyWeight);
  65   _avg_old_live       = new AdaptiveWeightedAverage(AdaptiveSizePolicyWeight);
  66   _avg_eden_live      = new AdaptiveWeightedAverage(AdaptiveSizePolicyWeight);
  67 
  68   _avg_survived       = new AdaptivePaddedAverage(AdaptiveSizePolicyWeight,
  69                                                   SurvivorPadding);
  70   _avg_pretenured     = new AdaptivePaddedNoZeroDevAverage(
  71                                                   AdaptiveSizePolicyWeight,
  72                                                   SurvivorPadding);
  73 
  74   _minor_pause_old_estimator =
  75     new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
  76   _minor_pause_young_estimator =
  77     new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
  78   _minor_collection_estimator =
  79     new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
  80   _major_collection_estimator =
  81     new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
  82 
  83   // Start the timers
  84   _minor_timer.start();
  85 
  86   _young_gen_policy_is_ready = false;
  87 }
  88 
  89 bool AdaptiveSizePolicy::tenuring_threshold_change() const {
  90   return decrement_tenuring_threshold_for_gc_cost() ||
  91          increment_tenuring_threshold_for_gc_cost() ||
  92          decrement_tenuring_threshold_for_survivor_limit();
  93 }
  94 
  95 void AdaptiveSizePolicy::minor_collection_begin() {
  96   // Update the interval time
  97   _minor_timer.stop();
  98   // Save most recent collection time
  99   _latest_minor_mutator_interval_seconds = _minor_timer.seconds();
 100   _minor_timer.reset();
 101   _minor_timer.start();
 102 }
 103 
 104 void AdaptiveSizePolicy::update_minor_pause_young_estimator(
 105     double minor_pause_in_ms) {
 106   double eden_size_in_mbytes = ((double)_eden_size)/((double)M);
 107   _minor_pause_young_estimator->update(eden_size_in_mbytes,
 108     minor_pause_in_ms);
 109 }
 110 
 111 void AdaptiveSizePolicy::minor_collection_end(GCCause::Cause gc_cause) {
 112   // Update the pause time.
 113   _minor_timer.stop();
 114 
 115   if (!GCCause::is_user_requested_gc(gc_cause) ||
 116       UseAdaptiveSizePolicyWithSystemGC) {
 117     double minor_pause_in_seconds = _minor_timer.seconds();
 118     double minor_pause_in_ms = minor_pause_in_seconds * MILLIUNITS;
 119 
 120     // Sample for performance counter
 121     _avg_minor_pause->sample(minor_pause_in_seconds);
 122 
 123     // Cost of collection (unit-less)
 124     double collection_cost = 0.0;
 125     if ((_latest_minor_mutator_interval_seconds > 0.0) &&
 126         (minor_pause_in_seconds > 0.0)) {
 127       double interval_in_seconds =
 128         _latest_minor_mutator_interval_seconds + minor_pause_in_seconds;
 129       collection_cost =
 130         minor_pause_in_seconds / interval_in_seconds;
 131       _avg_minor_gc_cost->sample(collection_cost);
 132       // Sample for performance counter
 133       _avg_minor_interval->sample(interval_in_seconds);
 134     }
 135 
 136     // The policy does not have enough data until at least some
 137     // young collections have been done.
 138     _young_gen_policy_is_ready =
 139       (_avg_minor_gc_cost->count() >= AdaptiveSizePolicyReadyThreshold);
 140 
 141     // Calculate variables used to estimate pause time vs. gen sizes
 142     double eden_size_in_mbytes = ((double)_eden_size) / ((double)M);
 143     update_minor_pause_young_estimator(minor_pause_in_ms);
 144     update_minor_pause_old_estimator(minor_pause_in_ms);
 145 
 146     log_trace(gc, ergo)("AdaptiveSizePolicy::minor_collection_end: minor gc cost: %f  average: %f",
 147                         collection_cost, _avg_minor_gc_cost->average());
 148     log_trace(gc, ergo)("  minor pause: %f minor period %f",
 149                         minor_pause_in_ms, _latest_minor_mutator_interval_seconds * MILLIUNITS);
 150 
 151     // Calculate variable used to estimate collection cost vs. gen sizes
 152     assert(collection_cost >= 0.0, "Expected to be non-negative");
 153     _minor_collection_estimator->update(eden_size_in_mbytes, collection_cost);
 154   }
 155 
 156   // Interval times use this timer to measure the mutator time.
 157   // Reset the timer after the GC pause.
 158   _minor_timer.reset();
 159   _minor_timer.start();
 160 }
 161 
 162 size_t AdaptiveSizePolicy::eden_increment(size_t cur_eden, uint percent_change) {
 163   size_t eden_heap_delta;
 164   eden_heap_delta = cur_eden / 100 * percent_change;
 165   return eden_heap_delta;
 166 }
 167 
 168 size_t AdaptiveSizePolicy::eden_increment(size_t cur_eden) {
 169   return eden_increment(cur_eden, YoungGenerationSizeIncrement);
 170 }
 171 
 172 size_t AdaptiveSizePolicy::eden_decrement(size_t cur_eden) {
 173   size_t eden_heap_delta = eden_increment(cur_eden) /
 174     AdaptiveSizeDecrementScaleFactor;
 175   return eden_heap_delta;
 176 }
 177 
 178 size_t AdaptiveSizePolicy::promo_increment(size_t cur_promo, uint percent_change) {
 179   size_t promo_heap_delta;
 180   promo_heap_delta = cur_promo / 100 * percent_change;
 181   return promo_heap_delta;
 182 }
 183 
 184 size_t AdaptiveSizePolicy::promo_increment(size_t cur_promo) {
 185   return promo_increment(cur_promo, TenuredGenerationSizeIncrement);
 186 }
 187 
 188 size_t AdaptiveSizePolicy::promo_decrement(size_t cur_promo) {
 189   size_t promo_heap_delta = promo_increment(cur_promo);
 190   promo_heap_delta = promo_heap_delta / AdaptiveSizeDecrementScaleFactor;
 191   return promo_heap_delta;
 192 }
 193 
 194 double AdaptiveSizePolicy::time_since_major_gc() const {
 195   _major_timer.stop();
 196   double result = _major_timer.seconds();
 197   _major_timer.start();
 198   return result;
 199 }
 200 
 201 // Linear decay of major gc cost
 202 double AdaptiveSizePolicy::decaying_major_gc_cost() const {
 203   double major_interval = major_gc_interval_average_for_decay();
 204   double major_gc_cost_average = major_gc_cost();
 205   double decayed_major_gc_cost = major_gc_cost_average;
 206   if(time_since_major_gc() > 0.0) {
 207     decayed_major_gc_cost = major_gc_cost() *
 208       (((double) AdaptiveSizeMajorGCDecayTimeScale) * major_interval)
 209       / time_since_major_gc();
 210   }
 211 
 212   // The decayed cost should always be smaller than the
 213   // average cost but the vagaries of finite arithmetic could
 214   // produce a larger value in decayed_major_gc_cost so protect
 215   // against that.
 216   return MIN2(major_gc_cost_average, decayed_major_gc_cost);
 217 }
 218 
 219 // Use a value of the major gc cost that has been decayed
 220 // by the factor
 221 //
 222 //      average-interval-between-major-gc * AdaptiveSizeMajorGCDecayTimeScale /
 223 //        time-since-last-major-gc
 224 //
 225 // if the average-interval-between-major-gc * AdaptiveSizeMajorGCDecayTimeScale
 226 // is less than time-since-last-major-gc.
 227 //
 228 // In cases where there are initial major gc's that
 229 // are of a relatively high cost but no later major
 230 // gc's, the total gc cost can remain high because
 231 // the major gc cost remains unchanged (since there are no major
 232 // gc's).  In such a situation the value of the unchanging
 233 // major gc cost can keep the mutator throughput below
 234 // the goal when in fact the major gc cost is becoming diminishingly
 235 // small.  Use the decaying gc cost only to decide whether to
 236 // adjust for throughput.  Using it also to determine the adjustment
 237 // to be made for throughput also seems reasonable but there is
 238 // no test case to use to decide if it is the right thing to do
 239 // don't do it yet.
 240 
 241 double AdaptiveSizePolicy::decaying_gc_cost() const {
 242   double decayed_major_gc_cost = major_gc_cost();
 243   double avg_major_interval = major_gc_interval_average_for_decay();
 244   if (UseAdaptiveSizeDecayMajorGCCost &&
 245       (AdaptiveSizeMajorGCDecayTimeScale > 0) &&
 246       (avg_major_interval > 0.00)) {
 247     double time_since_last_major_gc = time_since_major_gc();
 248 
 249     // Decay the major gc cost?
 250     if (time_since_last_major_gc >
 251         ((double) AdaptiveSizeMajorGCDecayTimeScale) * avg_major_interval) {
 252 
 253       // Decay using the time-since-last-major-gc
 254       decayed_major_gc_cost = decaying_major_gc_cost();
 255       log_trace(gc, ergo)("decaying_gc_cost: major interval average: %f  time since last major gc: %f",
 256                     avg_major_interval, time_since_last_major_gc);
 257       log_trace(gc, ergo)("  major gc cost: %f  decayed major gc cost: %f",
 258                     major_gc_cost(), decayed_major_gc_cost);
 259     }
 260   }
 261   double result = MIN2(1.0, decayed_major_gc_cost + minor_gc_cost());
 262   return result;
 263 }
 264 
 265 
 266 void AdaptiveSizePolicy::clear_generation_free_space_flags() {
 267   set_change_young_gen_for_min_pauses(0);
 268   set_change_old_gen_for_maj_pauses(0);
 269 
 270   set_change_old_gen_for_throughput(0);
 271   set_change_young_gen_for_throughput(0);
 272   set_decrease_for_footprint(0);
 273   set_decide_at_full_gc(0);
 274 }
 275 
 276 class AdaptiveSizePolicyTimeOverheadTester: public OverheadTester {
 277   double _gc_cost;
 278 
 279  public:
 280   AdaptiveSizePolicyTimeOverheadTester(double gc_cost) : _gc_cost(gc_cost) {}
 281 
 282   bool is_exceeded() {
 283     // Note that the gc time limit test only works for the collections
 284     // of the young gen + tenured gen and not for collections of the
 285     // permanent gen.  That is because the calculation of the space
 286     // freed by the collection is the free space in the young gen +
 287     // tenured gen.
 288     return _gc_cost > (GCTimeLimit / 100.0);
 289   }
 290 };
 291 
 292 class AdaptiveSizePolicySpaceOverheadTester: public OverheadTester {
 293   size_t _eden_live;
 294   size_t _max_old_gen_size;
 295   size_t _max_eden_size;
 296   size_t _promo_size;
 297   double _avg_eden_live;
 298   double _avg_old_live;
 299 
 300  public:
 301   AdaptiveSizePolicySpaceOverheadTester(size_t eden_live,
 302                                         size_t max_old_gen_size,
 303                                         size_t max_eden_size,
 304                                         size_t promo_size,
 305                                         double avg_eden_live,
 306                                         double avg_old_live) :
 307     _eden_live(eden_live),
 308     _max_old_gen_size(max_old_gen_size),
 309     _max_eden_size(max_eden_size),
 310     _promo_size(promo_size),
 311     _avg_eden_live(avg_eden_live),
 312     _avg_old_live(avg_old_live) {}
 313 
 314   bool is_exceeded() {
 315     // _max_eden_size is the upper limit on the size of eden based on
 316     // the maximum size of the young generation and the sizes
 317     // of the survivor space.
 318     // The question being asked is whether the space being recovered by
 319     // a collection is low.
 320     // free_in_eden is the free space in eden after a collection and
 321     // free_in_old_gen is the free space in the old generation after
 322     // a collection.
 323     //
 324     // Use the minimum of the current value of the live in eden
 325     // or the average of the live in eden.
 326     // If the current value drops quickly, that should be taken
 327     // into account (i.e., don't trigger if the amount of free
 328     // space has suddenly jumped up).  If the current is much
 329     // higher than the average, use the average since it represents
 330     // the longer term behavior.
 331     const size_t live_in_eden =
 332       MIN2(_eden_live, (size_t)_avg_eden_live);
 333     const size_t free_in_eden = _max_eden_size > live_in_eden ?
 334       _max_eden_size - live_in_eden : 0;
 335     const size_t free_in_old_gen = (size_t)(_max_old_gen_size - _avg_old_live);
 336     const size_t total_free_limit = free_in_old_gen + free_in_eden;
 337     const size_t total_mem = _max_old_gen_size + _max_eden_size;
 338     const double free_limit_ratio = GCHeapFreeLimit / 100.0;
 339     const double mem_free_limit = total_mem * free_limit_ratio;
 340     const double mem_free_old_limit = _max_old_gen_size * free_limit_ratio;
 341     const double mem_free_eden_limit = _max_eden_size * free_limit_ratio;
 342     size_t promo_limit = (size_t)(_max_old_gen_size - _avg_old_live);
 343     // But don't force a promo size below the current promo size. Otherwise,
 344     // the promo size will shrink for no good reason.
 345     promo_limit = MAX2(promo_limit, _promo_size);
 346 
 347     log_trace(gc, ergo)(
 348           "AdaptiveSizePolicySpaceOverheadTester::is_exceeded:"
 349           " promo_limit: " SIZE_FORMAT
 350           " max_eden_size: " SIZE_FORMAT
 351           " total_free_limit: " SIZE_FORMAT
 352           " max_old_gen_size: " SIZE_FORMAT
 353           " max_eden_size: " SIZE_FORMAT
 354           " mem_free_limit: " SIZE_FORMAT,
 355           promo_limit, _max_eden_size, total_free_limit,
 356           _max_old_gen_size, _max_eden_size,
 357           (size_t)mem_free_limit);
 358 
 359     return free_in_old_gen < (size_t)mem_free_old_limit &&
 360            free_in_eden < (size_t)mem_free_eden_limit;
 361   }
 362 
 363 };
 364 
 365 void AdaptiveSizePolicy::check_gc_overhead_limit(
 366                                           size_t eden_live,
 367                                           size_t max_old_gen_size,
 368                                           size_t max_eden_size,
 369                                           bool   is_full_gc,
 370                                           GCCause::Cause gc_cause,
 371                                           SoftRefPolicy* soft_ref_policy) {
 372 
 373   AdaptiveSizePolicyTimeOverheadTester time_overhead(gc_cost());
 374   AdaptiveSizePolicySpaceOverheadTester space_overhead(eden_live,
 375                                                        max_old_gen_size,
 376                                                        max_eden_size,
 377                                                        _promo_size,
 378                                                        avg_eden_live()->average(),
 379                                                        avg_old_live()->average());
 380   _overhead_checker.check_gc_overhead_limit(&time_overhead,
 381                                             &space_overhead,
 382                                             is_full_gc,
 383                                             gc_cause,
 384                                             soft_ref_policy);
 385 }
 386 // Printing
 387 
 388 bool AdaptiveSizePolicy::print() const {
 389   assert(UseAdaptiveSizePolicy, "UseAdaptiveSizePolicy need to be enabled.");
 390 
 391   if (!log_is_enabled(Debug, gc, ergo)) {
 392     return false;
 393   }
 394 
 395   // Print goal for which action is needed.
 396   char* action = NULL;
 397   bool change_for_pause = false;
 398   if ((change_old_gen_for_maj_pauses() ==
 399          decrease_old_gen_for_maj_pauses_true) ||
 400       (change_young_gen_for_min_pauses() ==
 401          decrease_young_gen_for_min_pauses_true)) {
 402     action = (char*) " *** pause time goal ***";
 403     change_for_pause = true;
 404   } else if ((change_old_gen_for_throughput() ==
 405                increase_old_gen_for_throughput_true) ||
 406             (change_young_gen_for_throughput() ==
 407                increase_young_gen_for_througput_true)) {
 408     action = (char*) " *** throughput goal ***";
 409   } else if (decrease_for_footprint()) {
 410     action = (char*) " *** reduced footprint ***";
 411   } else {
 412     // No actions were taken.  This can legitimately be the
 413     // situation if not enough data has been gathered to make
 414     // decisions.
 415     return false;
 416   }
 417 
 418   // Pauses
 419   // Currently the size of the old gen is only adjusted to
 420   // change the major pause times.
 421   char* young_gen_action = NULL;
 422   char* tenured_gen_action = NULL;
 423 
 424   char* shrink_msg = (char*) "(attempted to shrink)";
 425   char* grow_msg = (char*) "(attempted to grow)";
 426   char* no_change_msg = (char*) "(no change)";
 427   if (change_young_gen_for_min_pauses() ==
 428       decrease_young_gen_for_min_pauses_true) {
 429     young_gen_action = shrink_msg;
 430   } else if (change_for_pause) {
 431     young_gen_action = no_change_msg;
 432   }
 433 
 434   if (change_old_gen_for_maj_pauses() == decrease_old_gen_for_maj_pauses_true) {
 435     tenured_gen_action = shrink_msg;
 436   } else if (change_for_pause) {
 437     tenured_gen_action = no_change_msg;
 438   }
 439 
 440   // Throughput
 441   if (change_old_gen_for_throughput() == increase_old_gen_for_throughput_true) {
 442     assert(change_young_gen_for_throughput() ==
 443            increase_young_gen_for_througput_true,
 444            "Both generations should be growing");
 445     young_gen_action = grow_msg;
 446     tenured_gen_action = grow_msg;
 447   } else if (change_young_gen_for_throughput() ==
 448              increase_young_gen_for_througput_true) {
 449     // Only the young generation may grow at start up (before
 450     // enough full collections have been done to grow the old generation).
 451     young_gen_action = grow_msg;
 452     tenured_gen_action = no_change_msg;
 453   }
 454 
 455   // Minimum footprint
 456   if (decrease_for_footprint() != 0) {
 457     young_gen_action = shrink_msg;
 458     tenured_gen_action = shrink_msg;
 459   }
 460 
 461   log_debug(gc, ergo)("UseAdaptiveSizePolicy actions to meet %s", action);
 462   log_debug(gc, ergo)("                       GC overhead (%%)");
 463   log_debug(gc, ergo)("    Young generation:     %7.2f\t  %s",
 464                       100.0 * avg_minor_gc_cost()->average(), young_gen_action);
 465   log_debug(gc, ergo)("    Tenured generation:   %7.2f\t  %s",
 466                       100.0 * avg_major_gc_cost()->average(), tenured_gen_action);
 467   return true;
 468 }
 469 
 470 void AdaptiveSizePolicy::print_tenuring_threshold( uint new_tenuring_threshold_arg) const {
 471   // Tenuring threshold
 472   if (decrement_tenuring_threshold_for_survivor_limit()) {
 473     log_debug(gc, ergo)("Tenuring threshold: (attempted to decrease to avoid survivor space overflow) = %u", new_tenuring_threshold_arg);
 474   } else if (decrement_tenuring_threshold_for_gc_cost()) {
 475     log_debug(gc, ergo)("Tenuring threshold: (attempted to decrease to balance GC costs) = %u", new_tenuring_threshold_arg);
 476   } else if (increment_tenuring_threshold_for_gc_cost()) {
 477     log_debug(gc, ergo)("Tenuring threshold: (attempted to increase to balance GC costs) = %u", new_tenuring_threshold_arg);
 478   } else {
 479     assert(!tenuring_threshold_change(), "(no change was attempted)");
 480   }
 481 }