1 /*
   2  * Copyright (c) 2002, 2015, 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/parallel/parallelScavengeHeap.hpp"
  27 #include "gc/parallel/psAdaptiveSizePolicy.hpp"
  28 #include "gc/parallel/psGCAdaptivePolicyCounters.hpp"
  29 #include "gc/parallel/psScavenge.hpp"
  30 #include "gc/shared/collectorPolicy.hpp"
  31 #include "gc/shared/gcCause.hpp"
  32 #include "gc/shared/gcPolicyCounters.hpp"
  33 #include "runtime/timer.hpp"
  34 #include "utilities/top.hpp"
  35 
  36 #include <math.h>
  37 
  38 PSAdaptiveSizePolicy::PSAdaptiveSizePolicy(size_t init_eden_size,
  39                                            size_t init_promo_size,
  40                                            size_t init_survivor_size,
  41                                            size_t space_alignment,
  42                                            double gc_pause_goal_sec,
  43                                            double gc_minor_pause_goal_sec,
  44                                            uint gc_cost_ratio) :
  45      AdaptiveSizePolicy(init_eden_size,
  46                         init_promo_size,
  47                         init_survivor_size,
  48                         gc_pause_goal_sec,
  49                         gc_cost_ratio),
  50      _collection_cost_margin_fraction(AdaptiveSizePolicyCollectionCostMargin / 100.0),
  51      _space_alignment(space_alignment),
  52      _live_at_last_full_gc(init_promo_size),
  53      _gc_minor_pause_goal_sec(gc_minor_pause_goal_sec),
  54      _latest_major_mutator_interval_seconds(0),
  55      _young_gen_change_for_major_pause_count(0)
  56 {
  57   // Sizing policy statistics
  58   _avg_major_pause    =
  59     new AdaptivePaddedAverage(AdaptiveTimeWeight, PausePadding);
  60   _avg_minor_interval = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
  61   _avg_major_interval = new AdaptiveWeightedAverage(AdaptiveTimeWeight);
  62 
  63   _avg_base_footprint = new AdaptiveWeightedAverage(AdaptiveSizePolicyWeight);
  64   _major_pause_old_estimator =
  65     new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
  66   _major_pause_young_estimator =
  67     new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
  68   _major_collection_estimator =
  69     new LinearLeastSquareFit(AdaptiveSizePolicyWeight);
  70 
  71   _young_gen_size_increment_supplement = YoungGenerationSizeSupplement;
  72   _old_gen_size_increment_supplement = TenuredGenerationSizeSupplement;
  73 
  74   // Start the timers
  75   _major_timer.start();
  76 
  77   _old_gen_policy_is_ready = false;
  78 }
  79 
  80 size_t PSAdaptiveSizePolicy::calculate_free_based_on_live(size_t live, uintx ratio_as_percentage) {
  81   // We want to calculate how much free memory there can be based on the
  82   // amount of live data currently in the old gen. Using the formula:
  83   // ratio * (free + live) = free
  84   // Some equation solving later we get:
  85   // free = (live * ratio) / (1 - ratio)
  86 
  87   const double ratio = ratio_as_percentage / 100.0;
  88   const double ratio_inverse = 1.0 - ratio;
  89   const double tmp = live * ratio;
  90   size_t free = (size_t)(tmp / ratio_inverse);
  91 
  92   return free;
  93 }
  94 
  95 size_t PSAdaptiveSizePolicy::calculated_old_free_size_in_bytes() const {
  96   size_t free_size = (size_t)(_promo_size + avg_promoted()->padded_average());
  97   size_t live = ParallelScavengeHeap::heap()->old_gen()->used_in_bytes();
  98 
  99   if (MinHeapFreeRatio != 0) {
 100     size_t min_free = calculate_free_based_on_live(live, MinHeapFreeRatio);
 101     free_size = MAX2(free_size, min_free);
 102   }
 103 
 104   if (MaxHeapFreeRatio != 100) {
 105     size_t max_free = calculate_free_based_on_live(live, MaxHeapFreeRatio);
 106     free_size = MIN2(max_free, free_size);
 107   }
 108 
 109   return free_size;
 110 }
 111 
 112 void PSAdaptiveSizePolicy::major_collection_begin() {
 113   // Update the interval time
 114   _major_timer.stop();
 115   // Save most recent collection time
 116   _latest_major_mutator_interval_seconds = _major_timer.seconds();
 117   _major_timer.reset();
 118   _major_timer.start();
 119 }
 120 
 121 void PSAdaptiveSizePolicy::update_minor_pause_old_estimator(
 122     double minor_pause_in_ms) {
 123   double promo_size_in_mbytes = ((double)_promo_size)/((double)M);
 124   _minor_pause_old_estimator->update(promo_size_in_mbytes,
 125     minor_pause_in_ms);
 126 }
 127 
 128 void PSAdaptiveSizePolicy::major_collection_end(size_t amount_live,
 129   GCCause::Cause gc_cause) {
 130   // Update the pause time.
 131   _major_timer.stop();
 132 
 133   if (should_update_promo_stats(gc_cause)) {
 134     double major_pause_in_seconds = _major_timer.seconds();
 135     double major_pause_in_ms = major_pause_in_seconds * MILLIUNITS;
 136 
 137     // Sample for performance counter
 138     _avg_major_pause->sample(major_pause_in_seconds);
 139 
 140     // Cost of collection (unit-less)
 141     double collection_cost = 0.0;
 142     if ((_latest_major_mutator_interval_seconds > 0.0) &&
 143         (major_pause_in_seconds > 0.0)) {
 144       double interval_in_seconds =
 145         _latest_major_mutator_interval_seconds + major_pause_in_seconds;
 146       collection_cost =
 147         major_pause_in_seconds / interval_in_seconds;
 148       avg_major_gc_cost()->sample(collection_cost);
 149 
 150       // Sample for performance counter
 151       _avg_major_interval->sample(interval_in_seconds);
 152     }
 153 
 154     // Calculate variables used to estimate pause time vs. gen sizes
 155     double eden_size_in_mbytes = ((double)_eden_size)/((double)M);
 156     double promo_size_in_mbytes = ((double)_promo_size)/((double)M);
 157     _major_pause_old_estimator->update(promo_size_in_mbytes,
 158       major_pause_in_ms);
 159     _major_pause_young_estimator->update(eden_size_in_mbytes,
 160       major_pause_in_ms);
 161 
 162     if (PrintAdaptiveSizePolicy && Verbose) {
 163       gclog_or_tty->print("psAdaptiveSizePolicy::major_collection_end: "
 164         "major gc cost: %f  average: %f", collection_cost,
 165         avg_major_gc_cost()->average());
 166       gclog_or_tty->print_cr("  major pause: %f major period %f",
 167         major_pause_in_ms,
 168         _latest_major_mutator_interval_seconds * MILLIUNITS);
 169     }
 170 
 171     // Calculate variable used to estimate collection cost vs. gen sizes
 172     assert(collection_cost >= 0.0, "Expected to be non-negative");
 173     _major_collection_estimator->update(promo_size_in_mbytes,
 174         collection_cost);
 175   }
 176 
 177   // Update the amount live at the end of a full GC
 178   _live_at_last_full_gc = amount_live;
 179 
 180   // The policy does not have enough data until at least some major collections
 181   // have been done.
 182   if (_avg_major_pause->count() >= AdaptiveSizePolicyReadyThreshold) {
 183     _old_gen_policy_is_ready = true;
 184   }
 185 
 186   // Interval times use this timer to measure the interval that
 187   // the mutator runs.  Reset after the GC pause has been measured.
 188   _major_timer.reset();
 189   _major_timer.start();
 190 }
 191 
 192 // If the remaining free space in the old generation is less that
 193 // that expected to be needed by the next collection, do a full
 194 // collection now.
 195 bool PSAdaptiveSizePolicy::should_full_GC(size_t old_free_in_bytes) {
 196 
 197   // A similar test is done in the scavenge's should_attempt_scavenge().  If
 198   // this is changed, decide if that test should also be changed.
 199   bool result = padded_average_promoted_in_bytes() > (float) old_free_in_bytes;
 200   if (PrintGCDetails && Verbose) {
 201     if (result) {
 202       gclog_or_tty->print("  full after scavenge: ");
 203     } else {
 204       gclog_or_tty->print("  no full after scavenge: ");
 205     }
 206     gclog_or_tty->print_cr(" average_promoted " SIZE_FORMAT
 207       " padded_average_promoted " SIZE_FORMAT
 208       " free in old gen " SIZE_FORMAT,
 209       (size_t) average_promoted_in_bytes(),
 210       (size_t) padded_average_promoted_in_bytes(),
 211       old_free_in_bytes);
 212   }
 213   return result;
 214 }
 215 
 216 void PSAdaptiveSizePolicy::clear_generation_free_space_flags() {
 217 
 218   AdaptiveSizePolicy::clear_generation_free_space_flags();
 219 
 220   set_change_old_gen_for_min_pauses(0);
 221 
 222   set_change_young_gen_for_maj_pauses(0);
 223 }
 224 
 225 // If this is not a full GC, only test and modify the young generation.
 226 
 227 void PSAdaptiveSizePolicy::compute_generations_free_space(
 228                                            size_t young_live,
 229                                            size_t eden_live,
 230                                            size_t old_live,
 231                                            size_t cur_eden,
 232                                            size_t max_old_gen_size,
 233                                            size_t max_eden_size,
 234                                            bool   is_full_gc) {
 235   compute_eden_space_size(young_live,
 236                           eden_live,
 237                           cur_eden,
 238                           max_eden_size,
 239                           is_full_gc);
 240 
 241   compute_old_gen_free_space(old_live,
 242                              cur_eden,
 243                              max_old_gen_size,
 244                              is_full_gc);
 245 }
 246 
 247 void PSAdaptiveSizePolicy::compute_eden_space_size(
 248                                            size_t young_live,
 249                                            size_t eden_live,
 250                                            size_t cur_eden,
 251                                            size_t max_eden_size,
 252                                            bool   is_full_gc) {
 253 
 254   // Update statistics
 255   // Time statistics are updated as we go, update footprint stats here
 256   _avg_base_footprint->sample(BaseFootPrintEstimate);
 257   avg_young_live()->sample(young_live);
 258   avg_eden_live()->sample(eden_live);
 259 
 260   // This code used to return if the policy was not ready , i.e.,
 261   // policy_is_ready() returning false.  The intent was that
 262   // decisions below needed major collection times and so could
 263   // not be made before two major collections.  A consequence was
 264   // adjustments to the young generation were not done until after
 265   // two major collections even if the minor collections times
 266   // exceeded the requested goals.  Now let the young generation
 267   // adjust for the minor collection times.  Major collection times
 268   // will be zero for the first collection and will naturally be
 269   // ignored.  Tenured generation adjustments are only made at the
 270   // full collections so until the second major collection has
 271   // been reached, no tenured generation adjustments will be made.
 272 
 273   // Until we know better, desired promotion size uses the last calculation
 274   size_t desired_promo_size = _promo_size;
 275 
 276   // Start eden at the current value.  The desired value that is stored
 277   // in _eden_size is not bounded by constraints of the heap and can
 278   // run away.
 279   //
 280   // As expected setting desired_eden_size to the current
 281   // value of desired_eden_size as a starting point
 282   // caused desired_eden_size to grow way too large and caused
 283   // an overflow down stream.  It may have improved performance in
 284   // some case but is dangerous.
 285   size_t desired_eden_size = cur_eden;
 286 
 287   // Cache some values. There's a bit of work getting these, so
 288   // we might save a little time.
 289   const double major_cost = major_gc_cost();
 290   const double minor_cost = minor_gc_cost();
 291 
 292   // This method sets the desired eden size.  That plus the
 293   // desired survivor space sizes sets the desired young generation
 294   // size.  This methods does not know what the desired survivor
 295   // size is but expects that other policy will attempt to make
 296   // the survivor sizes compatible with the live data in the
 297   // young generation.  This limit is an estimate of the space left
 298   // in the young generation after the survivor spaces have been
 299   // subtracted out.
 300   size_t eden_limit = max_eden_size;
 301 
 302   const double gc_cost_limit = GCTimeLimit / 100.0;
 303 
 304   // Which way should we go?
 305   // if pause requirement is not met
 306   //   adjust size of any generation with average paus exceeding
 307   //   the pause limit.  Adjust one pause at a time (the larger)
 308   //   and only make adjustments for the major pause at full collections.
 309   // else if throughput requirement not met
 310   //   adjust the size of the generation with larger gc time.  Only
 311   //   adjust one generation at a time.
 312   // else
 313   //   adjust down the total heap size.  Adjust down the larger of the
 314   //   generations.
 315 
 316   // Add some checks for a threshold for a change.  For example,
 317   // a change less than the necessary alignment is probably not worth
 318   // attempting.
 319 
 320 
 321   if ((_avg_minor_pause->padded_average() > gc_pause_goal_sec()) ||
 322       (_avg_major_pause->padded_average() > gc_pause_goal_sec())) {
 323     //
 324     // Check pauses
 325     //
 326     // Make changes only to affect one of the pauses (the larger)
 327     // at a time.
 328     adjust_eden_for_pause_time(is_full_gc, &desired_promo_size, &desired_eden_size);
 329 
 330   } else if (_avg_minor_pause->padded_average() > gc_minor_pause_goal_sec()) {
 331     // Adjust only for the minor pause time goal
 332     adjust_eden_for_minor_pause_time(is_full_gc, &desired_eden_size);
 333 
 334   } else if(adjusted_mutator_cost() < _throughput_goal) {
 335     // This branch used to require that (mutator_cost() > 0.0 in 1.4.2.
 336     // This sometimes resulted in skipping to the minimize footprint
 337     // code.  Change this to try and reduce GC time if mutator time is
 338     // negative for whatever reason.  Or for future consideration,
 339     // bail out of the code if mutator time is negative.
 340     //
 341     // Throughput
 342     //
 343     assert(major_cost >= 0.0, "major cost is < 0.0");
 344     assert(minor_cost >= 0.0, "minor cost is < 0.0");
 345     // Try to reduce the GC times.
 346     adjust_eden_for_throughput(is_full_gc, &desired_eden_size);
 347 
 348   } else {
 349 
 350     // Be conservative about reducing the footprint.
 351     //   Do a minimum number of major collections first.
 352     //   Have reasonable averages for major and minor collections costs.
 353     if (UseAdaptiveSizePolicyFootprintGoal &&
 354         young_gen_policy_is_ready() &&
 355         avg_major_gc_cost()->average() >= 0.0 &&
 356         avg_minor_gc_cost()->average() >= 0.0) {
 357       size_t desired_sum = desired_eden_size + desired_promo_size;
 358       desired_eden_size = adjust_eden_for_footprint(desired_eden_size, desired_sum);
 359     }
 360   }
 361 
 362   // Note we make the same tests as in the code block below;  the code
 363   // seems a little easier to read with the printing in another block.
 364   if (PrintAdaptiveSizePolicy) {
 365     if (desired_eden_size > eden_limit) {
 366       gclog_or_tty->print_cr(
 367             "PSAdaptiveSizePolicy::compute_eden_space_size limits:"
 368             " desired_eden_size: " SIZE_FORMAT
 369             " old_eden_size: " SIZE_FORMAT
 370             " eden_limit: " SIZE_FORMAT
 371             " cur_eden: " SIZE_FORMAT
 372             " max_eden_size: " SIZE_FORMAT
 373             " avg_young_live: " SIZE_FORMAT,
 374             desired_eden_size, _eden_size, eden_limit, cur_eden,
 375             max_eden_size, (size_t)avg_young_live()->average());
 376     }
 377     if (gc_cost() > gc_cost_limit) {
 378       gclog_or_tty->print_cr(
 379             "PSAdaptiveSizePolicy::compute_eden_space_size: gc time limit"
 380             " gc_cost: %f "
 381             " GCTimeLimit: " UINTX_FORMAT,
 382             gc_cost(), GCTimeLimit);
 383     }
 384   }
 385 
 386   // Align everything and make a final limit check
 387   desired_eden_size  = align_size_up(desired_eden_size, _space_alignment);
 388   desired_eden_size  = MAX2(desired_eden_size, _space_alignment);
 389 
 390   eden_limit  = align_size_down(eden_limit, _space_alignment);
 391 
 392   // And one last limit check, now that we've aligned things.
 393   if (desired_eden_size > eden_limit) {
 394     // If the policy says to get a larger eden but
 395     // is hitting the limit, don't decrease eden.
 396     // This can lead to a general drifting down of the
 397     // eden size.  Let the tenuring calculation push more
 398     // into the old gen.
 399     desired_eden_size = MAX2(eden_limit, cur_eden);
 400   }
 401 
 402   if (PrintAdaptiveSizePolicy) {
 403     // Timing stats
 404     gclog_or_tty->print(
 405                "PSAdaptiveSizePolicy::compute_eden_space_size: costs"
 406                " minor_time: %f"
 407                " major_cost: %f"
 408                " mutator_cost: %f"
 409                " throughput_goal: %f",
 410                minor_gc_cost(), major_gc_cost(), mutator_cost(),
 411                _throughput_goal);
 412 
 413     // We give more details if Verbose is set
 414     if (Verbose) {
 415       gclog_or_tty->print( " minor_pause: %f"
 416                   " major_pause: %f"
 417                   " minor_interval: %f"
 418                   " major_interval: %f"
 419                   " pause_goal: %f",
 420                   _avg_minor_pause->padded_average(),
 421                   _avg_major_pause->padded_average(),
 422                   _avg_minor_interval->average(),
 423                   _avg_major_interval->average(),
 424                   gc_pause_goal_sec());
 425     }
 426 
 427     // Footprint stats
 428     gclog_or_tty->print( " live_space: " SIZE_FORMAT
 429                 " free_space: " SIZE_FORMAT,
 430                 live_space(), free_space());
 431     // More detail
 432     if (Verbose) {
 433       gclog_or_tty->print( " base_footprint: " SIZE_FORMAT
 434                   " avg_young_live: " SIZE_FORMAT
 435                   " avg_old_live: " SIZE_FORMAT,
 436                   (size_t)_avg_base_footprint->average(),
 437                   (size_t)avg_young_live()->average(),
 438                   (size_t)avg_old_live()->average());
 439     }
 440 
 441     // And finally, our old and new sizes.
 442     gclog_or_tty->print(" old_eden_size: " SIZE_FORMAT
 443                " desired_eden_size: " SIZE_FORMAT,
 444                _eden_size, desired_eden_size);
 445     gclog_or_tty->cr();
 446   }
 447 
 448   set_eden_size(desired_eden_size);
 449 }
 450 
 451 void PSAdaptiveSizePolicy::compute_old_gen_free_space(
 452                                            size_t old_live,
 453                                            size_t cur_eden,
 454                                            size_t max_old_gen_size,
 455                                            bool   is_full_gc) {
 456 
 457   // Update statistics
 458   // Time statistics are updated as we go, update footprint stats here
 459   if (is_full_gc) {
 460     // old_live is only accurate after a full gc
 461     avg_old_live()->sample(old_live);
 462   }
 463 
 464   // This code used to return if the policy was not ready , i.e.,
 465   // policy_is_ready() returning false.  The intent was that
 466   // decisions below needed major collection times and so could
 467   // not be made before two major collections.  A consequence was
 468   // adjustments to the young generation were not done until after
 469   // two major collections even if the minor collections times
 470   // exceeded the requested goals.  Now let the young generation
 471   // adjust for the minor collection times.  Major collection times
 472   // will be zero for the first collection and will naturally be
 473   // ignored.  Tenured generation adjustments are only made at the
 474   // full collections so until the second major collection has
 475   // been reached, no tenured generation adjustments will be made.
 476 
 477   // Until we know better, desired promotion size uses the last calculation
 478   size_t desired_promo_size = _promo_size;
 479 
 480   // Start eden at the current value.  The desired value that is stored
 481   // in _eden_size is not bounded by constraints of the heap and can
 482   // run away.
 483   //
 484   // As expected setting desired_eden_size to the current
 485   // value of desired_eden_size as a starting point
 486   // caused desired_eden_size to grow way too large and caused
 487   // an overflow down stream.  It may have improved performance in
 488   // some case but is dangerous.
 489   size_t desired_eden_size = cur_eden;
 490 
 491   // Cache some values. There's a bit of work getting these, so
 492   // we might save a little time.
 493   const double major_cost = major_gc_cost();
 494   const double minor_cost = minor_gc_cost();
 495 
 496   // Limits on our growth
 497   size_t promo_limit = (size_t)(max_old_gen_size - avg_old_live()->average());
 498 
 499   // But don't force a promo size below the current promo size. Otherwise,
 500   // the promo size will shrink for no good reason.
 501   promo_limit = MAX2(promo_limit, _promo_size);
 502 
 503   const double gc_cost_limit = GCTimeLimit/100.0;
 504 
 505   // Which way should we go?
 506   // if pause requirement is not met
 507   //   adjust size of any generation with average paus exceeding
 508   //   the pause limit.  Adjust one pause at a time (the larger)
 509   //   and only make adjustments for the major pause at full collections.
 510   // else if throughput requirement not met
 511   //   adjust the size of the generation with larger gc time.  Only
 512   //   adjust one generation at a time.
 513   // else
 514   //   adjust down the total heap size.  Adjust down the larger of the
 515   //   generations.
 516 
 517   // Add some checks for a threshold for a change.  For example,
 518   // a change less than the necessary alignment is probably not worth
 519   // attempting.
 520 
 521   if ((_avg_minor_pause->padded_average() > gc_pause_goal_sec()) ||
 522       (_avg_major_pause->padded_average() > gc_pause_goal_sec())) {
 523     //
 524     // Check pauses
 525     //
 526     // Make changes only to affect one of the pauses (the larger)
 527     // at a time.
 528     if (is_full_gc) {
 529       set_decide_at_full_gc(decide_at_full_gc_true);
 530       adjust_promo_for_pause_time(is_full_gc, &desired_promo_size, &desired_eden_size);
 531     }
 532   } else if (adjusted_mutator_cost() < _throughput_goal) {
 533     // This branch used to require that (mutator_cost() > 0.0 in 1.4.2.
 534     // This sometimes resulted in skipping to the minimize footprint
 535     // code.  Change this to try and reduce GC time if mutator time is
 536     // negative for whatever reason.  Or for future consideration,
 537     // bail out of the code if mutator time is negative.
 538     //
 539     // Throughput
 540     //
 541     assert(major_cost >= 0.0, "major cost is < 0.0");
 542     assert(minor_cost >= 0.0, "minor cost is < 0.0");
 543     // Try to reduce the GC times.
 544     if (is_full_gc) {
 545       set_decide_at_full_gc(decide_at_full_gc_true);
 546       adjust_promo_for_throughput(is_full_gc, &desired_promo_size);
 547     }
 548   } else {
 549 
 550     // Be conservative about reducing the footprint.
 551     //   Do a minimum number of major collections first.
 552     //   Have reasonable averages for major and minor collections costs.
 553     if (UseAdaptiveSizePolicyFootprintGoal &&
 554         young_gen_policy_is_ready() &&
 555         avg_major_gc_cost()->average() >= 0.0 &&
 556         avg_minor_gc_cost()->average() >= 0.0) {
 557       if (is_full_gc) {
 558         set_decide_at_full_gc(decide_at_full_gc_true);
 559         size_t desired_sum = desired_eden_size + desired_promo_size;
 560         desired_promo_size = adjust_promo_for_footprint(desired_promo_size, desired_sum);
 561       }
 562     }
 563   }
 564 
 565   // Note we make the same tests as in the code block below;  the code
 566   // seems a little easier to read with the printing in another block.
 567   if (PrintAdaptiveSizePolicy) {
 568     if (desired_promo_size > promo_limit)  {
 569       // "free_in_old_gen" was the original value for used for promo_limit
 570       size_t free_in_old_gen = (size_t)(max_old_gen_size - avg_old_live()->average());
 571       gclog_or_tty->print_cr(
 572             "PSAdaptiveSizePolicy::compute_old_gen_free_space limits:"
 573             " desired_promo_size: " SIZE_FORMAT
 574             " promo_limit: " SIZE_FORMAT
 575             " free_in_old_gen: " SIZE_FORMAT
 576             " max_old_gen_size: " SIZE_FORMAT
 577             " avg_old_live: " SIZE_FORMAT,
 578             desired_promo_size, promo_limit, free_in_old_gen,
 579             max_old_gen_size, (size_t) avg_old_live()->average());
 580     }
 581     if (gc_cost() > gc_cost_limit) {
 582       gclog_or_tty->print_cr(
 583             "PSAdaptiveSizePolicy::compute_old_gen_free_space: gc time limit"
 584             " gc_cost: %f "
 585             " GCTimeLimit: " UINTX_FORMAT,
 586             gc_cost(), GCTimeLimit);
 587     }
 588   }
 589 
 590   // Align everything and make a final limit check
 591   desired_promo_size = align_size_up(desired_promo_size, _space_alignment);
 592   desired_promo_size = MAX2(desired_promo_size, _space_alignment);
 593 
 594   promo_limit = align_size_down(promo_limit, _space_alignment);
 595 
 596   // And one last limit check, now that we've aligned things.
 597   desired_promo_size = MIN2(desired_promo_size, promo_limit);
 598 
 599   if (PrintAdaptiveSizePolicy) {
 600     // Timing stats
 601     gclog_or_tty->print(
 602                "PSAdaptiveSizePolicy::compute_old_gen_free_space: costs"
 603                " minor_time: %f"
 604                " major_cost: %f"
 605                " mutator_cost: %f"
 606                " throughput_goal: %f",
 607                minor_gc_cost(), major_gc_cost(), mutator_cost(),
 608                _throughput_goal);
 609 
 610     // We give more details if Verbose is set
 611     if (Verbose) {
 612       gclog_or_tty->print( " minor_pause: %f"
 613                   " major_pause: %f"
 614                   " minor_interval: %f"
 615                   " major_interval: %f"
 616                   " pause_goal: %f",
 617                   _avg_minor_pause->padded_average(),
 618                   _avg_major_pause->padded_average(),
 619                   _avg_minor_interval->average(),
 620                   _avg_major_interval->average(),
 621                   gc_pause_goal_sec());
 622     }
 623 
 624     // Footprint stats
 625     gclog_or_tty->print( " live_space: " SIZE_FORMAT
 626                 " free_space: " SIZE_FORMAT,
 627                 live_space(), free_space());
 628     // More detail
 629     if (Verbose) {
 630       gclog_or_tty->print( " base_footprint: " SIZE_FORMAT
 631                   " avg_young_live: " SIZE_FORMAT
 632                   " avg_old_live: " SIZE_FORMAT,
 633                   (size_t)_avg_base_footprint->average(),
 634                   (size_t)avg_young_live()->average(),
 635                   (size_t)avg_old_live()->average());
 636     }
 637 
 638     // And finally, our old and new sizes.
 639     gclog_or_tty->print(" old_promo_size: " SIZE_FORMAT
 640                " desired_promo_size: " SIZE_FORMAT,
 641                _promo_size, desired_promo_size);
 642     gclog_or_tty->cr();
 643   }
 644 
 645   set_promo_size(desired_promo_size);
 646 }
 647 
 648 void PSAdaptiveSizePolicy::decay_supplemental_growth(bool is_full_gc) {
 649   // Decay the supplemental increment?  Decay the supplement growth
 650   // factor even if it is not used.  It is only meant to give a boost
 651   // to the initial growth and if it is not used, then it was not
 652   // needed.
 653   if (is_full_gc) {
 654     // Don't wait for the threshold value for the major collections.  If
 655     // here, the supplemental growth term was used and should decay.
 656     if ((_avg_major_pause->count() % TenuredGenerationSizeSupplementDecay)
 657         == 0) {
 658       _old_gen_size_increment_supplement =
 659         _old_gen_size_increment_supplement >> 1;
 660     }
 661   } else {
 662     if ((_avg_minor_pause->count() >= AdaptiveSizePolicyReadyThreshold) &&
 663         (_avg_minor_pause->count() % YoungGenerationSizeSupplementDecay) == 0) {
 664       _young_gen_size_increment_supplement =
 665         _young_gen_size_increment_supplement >> 1;
 666     }
 667   }
 668 }
 669 
 670 void PSAdaptiveSizePolicy::adjust_eden_for_minor_pause_time(bool is_full_gc,
 671     size_t* desired_eden_size_ptr) {
 672 
 673   // Adjust the young generation size to reduce pause time of
 674   // of collections.
 675   //
 676   // The AdaptiveSizePolicyInitializingSteps test is not used
 677   // here.  It has not seemed to be needed but perhaps should
 678   // be added for consistency.
 679   if (minor_pause_young_estimator()->decrement_will_decrease()) {
 680         // reduce eden size
 681     set_change_young_gen_for_min_pauses(
 682           decrease_young_gen_for_min_pauses_true);
 683     *desired_eden_size_ptr = *desired_eden_size_ptr -
 684       eden_decrement_aligned_down(*desired_eden_size_ptr);
 685     } else {
 686       // EXPERIMENTAL ADJUSTMENT
 687       // Only record that the estimator indicated such an action.
 688       // *desired_eden_size_ptr = *desired_eden_size_ptr + eden_heap_delta;
 689       set_change_young_gen_for_min_pauses(
 690           increase_young_gen_for_min_pauses_true);
 691   }
 692 }
 693 
 694 void PSAdaptiveSizePolicy::adjust_promo_for_pause_time(bool is_full_gc,
 695                                              size_t* desired_promo_size_ptr,
 696                                              size_t* desired_eden_size_ptr) {
 697 
 698   size_t promo_heap_delta = 0;
 699   // Add some checks for a threshold for a change.  For example,
 700   // a change less than the required alignment is probably not worth
 701   // attempting.
 702 
 703   if (_avg_minor_pause->padded_average() <= _avg_major_pause->padded_average() && is_full_gc) {
 704     // Adjust for the major pause time only at full gc's because the
 705     // affects of a change can only be seen at full gc's.
 706 
 707     // Reduce old generation size to reduce pause?
 708     if (major_pause_old_estimator()->decrement_will_decrease()) {
 709       // reduce old generation size
 710       set_change_old_gen_for_maj_pauses(decrease_old_gen_for_maj_pauses_true);
 711       promo_heap_delta = promo_decrement_aligned_down(*desired_promo_size_ptr);
 712       *desired_promo_size_ptr = _promo_size - promo_heap_delta;
 713     } else {
 714       // EXPERIMENTAL ADJUSTMENT
 715       // Only record that the estimator indicated such an action.
 716       // *desired_promo_size_ptr = _promo_size +
 717       //   promo_increment_aligned_up(*desired_promo_size_ptr);
 718       set_change_old_gen_for_maj_pauses(increase_old_gen_for_maj_pauses_true);
 719     }
 720   }
 721 
 722   if (PrintAdaptiveSizePolicy && Verbose) {
 723     gclog_or_tty->print_cr(
 724       "PSAdaptiveSizePolicy::adjust_promo_for_pause_time "
 725       "adjusting gen sizes for major pause (avg %f goal %f). "
 726       "desired_promo_size " SIZE_FORMAT " promo delta " SIZE_FORMAT,
 727       _avg_major_pause->average(), gc_pause_goal_sec(),
 728       *desired_promo_size_ptr, promo_heap_delta);
 729   }
 730 }
 731 
 732 void PSAdaptiveSizePolicy::adjust_eden_for_pause_time(bool is_full_gc,
 733                                              size_t* desired_promo_size_ptr,
 734                                              size_t* desired_eden_size_ptr) {
 735 
 736   size_t eden_heap_delta = 0;
 737   // Add some checks for a threshold for a change.  For example,
 738   // a change less than the required alignment is probably not worth
 739   // attempting.
 740   if (_avg_minor_pause->padded_average() > _avg_major_pause->padded_average()) {
 741     adjust_eden_for_minor_pause_time(is_full_gc, desired_eden_size_ptr);
 742   }
 743   if (PrintAdaptiveSizePolicy && Verbose) {
 744     gclog_or_tty->print_cr(
 745       "PSAdaptiveSizePolicy::adjust_eden_for_pause_time "
 746       "adjusting gen sizes for major pause (avg %f goal %f). "
 747       "desired_eden_size " SIZE_FORMAT " eden delta " SIZE_FORMAT,
 748       _avg_major_pause->average(), gc_pause_goal_sec(),
 749       *desired_eden_size_ptr, eden_heap_delta);
 750   }
 751 }
 752 
 753 void PSAdaptiveSizePolicy::adjust_promo_for_throughput(bool is_full_gc,
 754                                              size_t* desired_promo_size_ptr) {
 755 
 756   // Add some checks for a threshold for a change.  For example,
 757   // a change less than the required alignment is probably not worth
 758   // attempting.
 759 
 760   if ((gc_cost() + mutator_cost()) == 0.0) {
 761     return;
 762   }
 763 
 764   if (PrintAdaptiveSizePolicy && Verbose) {
 765     gclog_or_tty->print("\nPSAdaptiveSizePolicy::adjust_promo_for_throughput("
 766       "is_full: %d, promo: " SIZE_FORMAT "): ",
 767       is_full_gc, *desired_promo_size_ptr);
 768     gclog_or_tty->print_cr("mutator_cost %f  major_gc_cost %f "
 769       "minor_gc_cost %f", mutator_cost(), major_gc_cost(), minor_gc_cost());
 770   }
 771 
 772   // Tenured generation
 773   if (is_full_gc) {
 774     // Calculate the change to use for the tenured gen.
 775     size_t scaled_promo_heap_delta = 0;
 776     // Can the increment to the generation be scaled?
 777     if (gc_cost() >= 0.0 && major_gc_cost() >= 0.0) {
 778       size_t promo_heap_delta =
 779         promo_increment_with_supplement_aligned_up(*desired_promo_size_ptr);
 780       double scale_by_ratio = major_gc_cost() / gc_cost();
 781       scaled_promo_heap_delta =
 782         (size_t) (scale_by_ratio * (double) promo_heap_delta);
 783       if (PrintAdaptiveSizePolicy && Verbose) {
 784         gclog_or_tty->print_cr(
 785           "Scaled tenured increment: " SIZE_FORMAT " by %f down to "
 786           SIZE_FORMAT,
 787           promo_heap_delta, scale_by_ratio, scaled_promo_heap_delta);
 788       }
 789     } else if (major_gc_cost() >= 0.0) {
 790       // Scaling is not going to work.  If the major gc time is the
 791       // larger, give it a full increment.
 792       if (major_gc_cost() >= minor_gc_cost()) {
 793         scaled_promo_heap_delta =
 794           promo_increment_with_supplement_aligned_up(*desired_promo_size_ptr);
 795       }
 796     } else {
 797       // Don't expect to get here but it's ok if it does
 798       // in the product build since the delta will be 0
 799       // and nothing will change.
 800       assert(false, "Unexpected value for gc costs");
 801     }
 802 
 803     switch (AdaptiveSizeThroughPutPolicy) {
 804       case 1:
 805         // Early in the run the statistics might not be good.  Until
 806         // a specific number of collections have been, use the heuristic
 807         // that a larger generation size means lower collection costs.
 808         if (major_collection_estimator()->increment_will_decrease() ||
 809            (_old_gen_change_for_major_throughput
 810             <= AdaptiveSizePolicyInitializingSteps)) {
 811           // Increase tenured generation size to reduce major collection cost
 812           if ((*desired_promo_size_ptr + scaled_promo_heap_delta) >
 813               *desired_promo_size_ptr) {
 814             *desired_promo_size_ptr = _promo_size + scaled_promo_heap_delta;
 815           }
 816           set_change_old_gen_for_throughput(
 817               increase_old_gen_for_throughput_true);
 818               _old_gen_change_for_major_throughput++;
 819         } else {
 820           // EXPERIMENTAL ADJUSTMENT
 821           // Record that decreasing the old gen size would decrease
 822           // the major collection cost but don't do it.
 823           // *desired_promo_size_ptr = _promo_size -
 824           //   promo_decrement_aligned_down(*desired_promo_size_ptr);
 825           set_change_old_gen_for_throughput(
 826                 decrease_old_gen_for_throughput_true);
 827         }
 828 
 829         break;
 830       default:
 831         // Simplest strategy
 832         if ((*desired_promo_size_ptr + scaled_promo_heap_delta) >
 833             *desired_promo_size_ptr) {
 834           *desired_promo_size_ptr = *desired_promo_size_ptr +
 835             scaled_promo_heap_delta;
 836         }
 837         set_change_old_gen_for_throughput(
 838           increase_old_gen_for_throughput_true);
 839         _old_gen_change_for_major_throughput++;
 840     }
 841 
 842     if (PrintAdaptiveSizePolicy && Verbose) {
 843       gclog_or_tty->print_cr(
 844           "adjusting tenured gen for throughput (avg %f goal %f). "
 845           "desired_promo_size " SIZE_FORMAT " promo_delta " SIZE_FORMAT ,
 846           mutator_cost(), _throughput_goal,
 847           *desired_promo_size_ptr, scaled_promo_heap_delta);
 848     }
 849   }
 850 }
 851 
 852 void PSAdaptiveSizePolicy::adjust_eden_for_throughput(bool is_full_gc,
 853                                              size_t* desired_eden_size_ptr) {
 854 
 855   // Add some checks for a threshold for a change.  For example,
 856   // a change less than the required alignment is probably not worth
 857   // attempting.
 858 
 859   if ((gc_cost() + mutator_cost()) == 0.0) {
 860     return;
 861   }
 862 
 863   if (PrintAdaptiveSizePolicy && Verbose) {
 864     gclog_or_tty->print("\nPSAdaptiveSizePolicy::adjust_eden_for_throughput("
 865       "is_full: %d, cur_eden: " SIZE_FORMAT "): ",
 866       is_full_gc, *desired_eden_size_ptr);
 867     gclog_or_tty->print_cr("mutator_cost %f  major_gc_cost %f "
 868       "minor_gc_cost %f", mutator_cost(), major_gc_cost(), minor_gc_cost());
 869   }
 870 
 871   // Young generation
 872   size_t scaled_eden_heap_delta = 0;
 873   // Can the increment to the generation be scaled?
 874   if (gc_cost() >= 0.0 && minor_gc_cost() >= 0.0) {
 875     size_t eden_heap_delta =
 876       eden_increment_with_supplement_aligned_up(*desired_eden_size_ptr);
 877     double scale_by_ratio = minor_gc_cost() / gc_cost();
 878     assert(scale_by_ratio <= 1.0 && scale_by_ratio >= 0.0, "Scaling is wrong");
 879     scaled_eden_heap_delta =
 880       (size_t) (scale_by_ratio * (double) eden_heap_delta);
 881     if (PrintAdaptiveSizePolicy && Verbose) {
 882       gclog_or_tty->print_cr(
 883         "Scaled eden increment: " SIZE_FORMAT " by %f down to "
 884         SIZE_FORMAT,
 885         eden_heap_delta, scale_by_ratio, scaled_eden_heap_delta);
 886     }
 887   } else if (minor_gc_cost() >= 0.0) {
 888     // Scaling is not going to work.  If the minor gc time is the
 889     // larger, give it a full increment.
 890     if (minor_gc_cost() > major_gc_cost()) {
 891       scaled_eden_heap_delta =
 892         eden_increment_with_supplement_aligned_up(*desired_eden_size_ptr);
 893     }
 894   } else {
 895     // Don't expect to get here but it's ok if it does
 896     // in the product build since the delta will be 0
 897     // and nothing will change.
 898     assert(false, "Unexpected value for gc costs");
 899   }
 900 
 901   // Use a heuristic for some number of collections to give
 902   // the averages time to settle down.
 903   switch (AdaptiveSizeThroughPutPolicy) {
 904     case 1:
 905       if (minor_collection_estimator()->increment_will_decrease() ||
 906         (_young_gen_change_for_minor_throughput
 907           <= AdaptiveSizePolicyInitializingSteps)) {
 908         // Expand young generation size to reduce frequency of
 909         // of collections.
 910         if ((*desired_eden_size_ptr + scaled_eden_heap_delta) >
 911             *desired_eden_size_ptr) {
 912           *desired_eden_size_ptr =
 913             *desired_eden_size_ptr + scaled_eden_heap_delta;
 914         }
 915         set_change_young_gen_for_throughput(
 916           increase_young_gen_for_througput_true);
 917         _young_gen_change_for_minor_throughput++;
 918       } else {
 919         // EXPERIMENTAL ADJUSTMENT
 920         // Record that decreasing the young gen size would decrease
 921         // the minor collection cost but don't do it.
 922         // *desired_eden_size_ptr = _eden_size -
 923         //   eden_decrement_aligned_down(*desired_eden_size_ptr);
 924         set_change_young_gen_for_throughput(
 925           decrease_young_gen_for_througput_true);
 926       }
 927           break;
 928     default:
 929       if ((*desired_eden_size_ptr + scaled_eden_heap_delta) >
 930           *desired_eden_size_ptr) {
 931         *desired_eden_size_ptr =
 932           *desired_eden_size_ptr + scaled_eden_heap_delta;
 933       }
 934       set_change_young_gen_for_throughput(
 935         increase_young_gen_for_througput_true);
 936       _young_gen_change_for_minor_throughput++;
 937   }
 938 
 939   if (PrintAdaptiveSizePolicy && Verbose) {
 940     gclog_or_tty->print_cr(
 941         "adjusting eden for throughput (avg %f goal %f). desired_eden_size "
 942         SIZE_FORMAT " eden delta " SIZE_FORMAT "\n",
 943       mutator_cost(), _throughput_goal,
 944         *desired_eden_size_ptr, scaled_eden_heap_delta);
 945   }
 946 }
 947 
 948 size_t PSAdaptiveSizePolicy::adjust_promo_for_footprint(
 949     size_t desired_promo_size, size_t desired_sum) {
 950   assert(desired_promo_size <= desired_sum, "Inconsistent parameters");
 951   set_decrease_for_footprint(decrease_old_gen_for_footprint_true);
 952 
 953   size_t change = promo_decrement(desired_promo_size);
 954   change = scale_down(change, desired_promo_size, desired_sum);
 955 
 956   size_t reduced_size = desired_promo_size - change;
 957 
 958   if (PrintAdaptiveSizePolicy && Verbose) {
 959     gclog_or_tty->print_cr(
 960       "AdaptiveSizePolicy::adjust_promo_for_footprint "
 961       "adjusting tenured gen for footprint. "
 962       "starting promo size " SIZE_FORMAT
 963       " reduced promo size " SIZE_FORMAT
 964       " promo delta " SIZE_FORMAT,
 965       desired_promo_size, reduced_size, change );
 966   }
 967 
 968   assert(reduced_size <= desired_promo_size, "Inconsistent result");
 969   return reduced_size;
 970 }
 971 
 972 size_t PSAdaptiveSizePolicy::adjust_eden_for_footprint(
 973   size_t desired_eden_size, size_t desired_sum) {
 974   assert(desired_eden_size <= desired_sum, "Inconsistent parameters");
 975   set_decrease_for_footprint(decrease_young_gen_for_footprint_true);
 976 
 977   size_t change = eden_decrement(desired_eden_size);
 978   change = scale_down(change, desired_eden_size, desired_sum);
 979 
 980   size_t reduced_size = desired_eden_size - change;
 981 
 982   if (PrintAdaptiveSizePolicy && Verbose) {
 983     gclog_or_tty->print_cr(
 984       "AdaptiveSizePolicy::adjust_eden_for_footprint "
 985       "adjusting eden for footprint. "
 986       " starting eden size " SIZE_FORMAT
 987       " reduced eden size " SIZE_FORMAT
 988       " eden delta " SIZE_FORMAT,
 989       desired_eden_size, reduced_size, change);
 990   }
 991 
 992   assert(reduced_size <= desired_eden_size, "Inconsistent result");
 993   return reduced_size;
 994 }
 995 
 996 // Scale down "change" by the factor
 997 //      part / total
 998 // Don't align the results.
 999 
1000 size_t PSAdaptiveSizePolicy::scale_down(size_t change,
1001                                         double part,
1002                                         double total) {
1003   assert(part <= total, "Inconsistent input");
1004   size_t reduced_change = change;
1005   if (total > 0) {
1006     double fraction =  part / total;
1007     reduced_change = (size_t) (fraction * (double) change);
1008   }
1009   assert(reduced_change <= change, "Inconsistent result");
1010   return reduced_change;
1011 }
1012 
1013 size_t PSAdaptiveSizePolicy::eden_increment(size_t cur_eden,
1014                                             uint percent_change) {
1015   size_t eden_heap_delta;
1016   eden_heap_delta = cur_eden / 100 * percent_change;
1017   return eden_heap_delta;
1018 }
1019 
1020 size_t PSAdaptiveSizePolicy::eden_increment(size_t cur_eden) {
1021   return eden_increment(cur_eden, YoungGenerationSizeIncrement);
1022 }
1023 
1024 size_t PSAdaptiveSizePolicy::eden_increment_aligned_up(size_t cur_eden) {
1025   size_t result = eden_increment(cur_eden, YoungGenerationSizeIncrement);
1026   return align_size_up(result, _space_alignment);
1027 }
1028 
1029 size_t PSAdaptiveSizePolicy::eden_increment_aligned_down(size_t cur_eden) {
1030   size_t result = eden_increment(cur_eden);
1031   return align_size_down(result, _space_alignment);
1032 }
1033 
1034 size_t PSAdaptiveSizePolicy::eden_increment_with_supplement_aligned_up(
1035   size_t cur_eden) {
1036   size_t result = eden_increment(cur_eden,
1037     YoungGenerationSizeIncrement + _young_gen_size_increment_supplement);
1038   return align_size_up(result, _space_alignment);
1039 }
1040 
1041 size_t PSAdaptiveSizePolicy::eden_decrement_aligned_down(size_t cur_eden) {
1042   size_t eden_heap_delta = eden_decrement(cur_eden);
1043   return align_size_down(eden_heap_delta, _space_alignment);
1044 }
1045 
1046 size_t PSAdaptiveSizePolicy::eden_decrement(size_t cur_eden) {
1047   size_t eden_heap_delta = eden_increment(cur_eden) /
1048     AdaptiveSizeDecrementScaleFactor;
1049   return eden_heap_delta;
1050 }
1051 
1052 size_t PSAdaptiveSizePolicy::promo_increment(size_t cur_promo,
1053                                              uint percent_change) {
1054   size_t promo_heap_delta;
1055   promo_heap_delta = cur_promo / 100 * percent_change;
1056   return promo_heap_delta;
1057 }
1058 
1059 size_t PSAdaptiveSizePolicy::promo_increment(size_t cur_promo) {
1060   return promo_increment(cur_promo, TenuredGenerationSizeIncrement);
1061 }
1062 
1063 size_t PSAdaptiveSizePolicy::promo_increment_aligned_up(size_t cur_promo) {
1064   size_t result =  promo_increment(cur_promo, TenuredGenerationSizeIncrement);
1065   return align_size_up(result, _space_alignment);
1066 }
1067 
1068 size_t PSAdaptiveSizePolicy::promo_increment_aligned_down(size_t cur_promo) {
1069   size_t result =  promo_increment(cur_promo, TenuredGenerationSizeIncrement);
1070   return align_size_down(result, _space_alignment);
1071 }
1072 
1073 size_t PSAdaptiveSizePolicy::promo_increment_with_supplement_aligned_up(
1074   size_t cur_promo) {
1075   size_t result =  promo_increment(cur_promo,
1076     TenuredGenerationSizeIncrement + _old_gen_size_increment_supplement);
1077   return align_size_up(result, _space_alignment);
1078 }
1079 
1080 size_t PSAdaptiveSizePolicy::promo_decrement_aligned_down(size_t cur_promo) {
1081   size_t promo_heap_delta = promo_decrement(cur_promo);
1082   return align_size_down(promo_heap_delta, _space_alignment);
1083 }
1084 
1085 size_t PSAdaptiveSizePolicy::promo_decrement(size_t cur_promo) {
1086   size_t promo_heap_delta = promo_increment(cur_promo);
1087   promo_heap_delta = promo_heap_delta / AdaptiveSizeDecrementScaleFactor;
1088   return promo_heap_delta;
1089 }
1090 
1091 uint PSAdaptiveSizePolicy::compute_survivor_space_size_and_threshold(
1092                                              bool is_survivor_overflow,
1093                                              uint tenuring_threshold,
1094                                              size_t survivor_limit) {
1095   assert(survivor_limit >= _space_alignment,
1096          "survivor_limit too small");
1097   assert((size_t)align_size_down(survivor_limit, _space_alignment)
1098          == survivor_limit, "survivor_limit not aligned");
1099 
1100   // This method is called even if the tenuring threshold and survivor
1101   // spaces are not adjusted so that the averages are sampled above.
1102   if (!UsePSAdaptiveSurvivorSizePolicy ||
1103       !young_gen_policy_is_ready()) {
1104     return tenuring_threshold;
1105   }
1106 
1107   // We'll decide whether to increase or decrease the tenuring
1108   // threshold based partly on the newly computed survivor size
1109   // (if we hit the maximum limit allowed, we'll always choose to
1110   // decrement the threshold).
1111   bool incr_tenuring_threshold = false;
1112   bool decr_tenuring_threshold = false;
1113 
1114   set_decrement_tenuring_threshold_for_gc_cost(false);
1115   set_increment_tenuring_threshold_for_gc_cost(false);
1116   set_decrement_tenuring_threshold_for_survivor_limit(false);
1117 
1118   if (!is_survivor_overflow) {
1119     // Keep running averages on how much survived
1120 
1121     // We use the tenuring threshold to equalize the cost of major
1122     // and minor collections.
1123     // ThresholdTolerance is used to indicate how sensitive the
1124     // tenuring threshold is to differences in cost between the
1125     // collection types.
1126 
1127     // Get the times of interest. This involves a little work, so
1128     // we cache the values here.
1129     const double major_cost = major_gc_cost();
1130     const double minor_cost = minor_gc_cost();
1131 
1132     if (minor_cost > major_cost * _threshold_tolerance_percent) {
1133       // Minor times are getting too long;  lower the threshold so
1134       // less survives and more is promoted.
1135       decr_tenuring_threshold = true;
1136       set_decrement_tenuring_threshold_for_gc_cost(true);
1137     } else if (major_cost > minor_cost * _threshold_tolerance_percent) {
1138       // Major times are too long, so we want less promotion.
1139       incr_tenuring_threshold = true;
1140       set_increment_tenuring_threshold_for_gc_cost(true);
1141     }
1142 
1143   } else {
1144     // Survivor space overflow occurred, so promoted and survived are
1145     // not accurate. We'll make our best guess by combining survived
1146     // and promoted and count them as survivors.
1147     //
1148     // We'll lower the tenuring threshold to see if we can correct
1149     // things. Also, set the survivor size conservatively. We're
1150     // trying to avoid many overflows from occurring if defnew size
1151     // is just too small.
1152 
1153     decr_tenuring_threshold = true;
1154   }
1155 
1156   // The padded average also maintains a deviation from the average;
1157   // we use this to see how good of an estimate we have of what survived.
1158   // We're trying to pad the survivor size as little as possible without
1159   // overflowing the survivor spaces.
1160   size_t target_size = align_size_up((size_t)_avg_survived->padded_average(),
1161                                      _space_alignment);
1162   target_size = MAX2(target_size, _space_alignment);
1163 
1164   if (target_size > survivor_limit) {
1165     // Target size is bigger than we can handle. Let's also reduce
1166     // the tenuring threshold.
1167     target_size = survivor_limit;
1168     decr_tenuring_threshold = true;
1169     set_decrement_tenuring_threshold_for_survivor_limit(true);
1170   }
1171 
1172   // Finally, increment or decrement the tenuring threshold, as decided above.
1173   // We test for decrementing first, as we might have hit the target size
1174   // limit.
1175   if (decr_tenuring_threshold && !(AlwaysTenure || NeverTenure)) {
1176     if (tenuring_threshold > 1) {
1177       tenuring_threshold--;
1178     }
1179   } else if (incr_tenuring_threshold && !(AlwaysTenure || NeverTenure)) {
1180     if (tenuring_threshold < MaxTenuringThreshold) {
1181       tenuring_threshold++;
1182     }
1183   }
1184 
1185   // We keep a running average of the amount promoted which is used
1186   // to decide when we should collect the old generation (when
1187   // the amount of old gen free space is less than what we expect to
1188   // promote).
1189 
1190   if (PrintAdaptiveSizePolicy) {
1191     // A little more detail if Verbose is on
1192     if (Verbose) {
1193       gclog_or_tty->print( "  avg_survived: %f"
1194                   "  avg_deviation: %f",
1195                   _avg_survived->average(),
1196                   _avg_survived->deviation());
1197     }
1198 
1199     gclog_or_tty->print( "  avg_survived_padded_avg: %f",
1200                 _avg_survived->padded_average());
1201 
1202     if (Verbose) {
1203       gclog_or_tty->print( "  avg_promoted_avg: %f"
1204                   "  avg_promoted_dev: %f",
1205                   avg_promoted()->average(),
1206                   avg_promoted()->deviation());
1207     }
1208 
1209     gclog_or_tty->print_cr( "  avg_promoted_padded_avg: %f"
1210                 "  avg_pretenured_padded_avg: %f"
1211                 "  tenuring_thresh: %d"
1212                 "  target_size: " SIZE_FORMAT,
1213                 avg_promoted()->padded_average(),
1214                 _avg_pretenured->padded_average(),
1215                 tenuring_threshold, target_size);
1216   }
1217 
1218   set_survivor_size(target_size);
1219 
1220   return tenuring_threshold;
1221 }
1222 
1223 void PSAdaptiveSizePolicy::update_averages(bool is_survivor_overflow,
1224                                            size_t survived,
1225                                            size_t promoted) {
1226   // Update averages
1227   if (!is_survivor_overflow) {
1228     // Keep running averages on how much survived
1229     _avg_survived->sample(survived);
1230   } else {
1231     size_t survived_guess = survived + promoted;
1232     _avg_survived->sample(survived_guess);
1233   }
1234   avg_promoted()->sample(promoted);
1235 
1236   if (PrintAdaptiveSizePolicy) {
1237     gclog_or_tty->print_cr(
1238                   "AdaptiveSizePolicy::update_averages:"
1239                   "  survived: "  SIZE_FORMAT
1240                   "  promoted: "  SIZE_FORMAT
1241                   "  overflow: %s",
1242                   survived, promoted, is_survivor_overflow ? "true" : "false");
1243   }
1244 }
1245 
1246 bool PSAdaptiveSizePolicy::print_adaptive_size_policy_on(outputStream* st)
1247   const {
1248 
1249   if (!UseAdaptiveSizePolicy) return false;
1250 
1251   return AdaptiveSizePolicy::print_adaptive_size_policy_on(
1252                           st,
1253                           PSScavenge::tenuring_threshold());
1254 }
1255 
1256 #ifndef PRODUCT
1257 
1258 void TestOldFreeSpaceCalculation_test() {
1259   assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(100, 20) == 25, "Calculation of free memory failed");
1260   assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(100, 50) == 100, "Calculation of free memory failed");
1261   assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(100, 60) == 150, "Calculation of free memory failed");
1262   assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(100, 75) == 300, "Calculation of free memory failed");
1263   assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(400, 20) == 100, "Calculation of free memory failed");
1264   assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(400, 50) == 400, "Calculation of free memory failed");
1265   assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(400, 60) == 600, "Calculation of free memory failed");
1266   assert(PSAdaptiveSizePolicy::calculate_free_based_on_live(400, 75) == 1200, "Calculation of free memory failed");
1267 }
1268 
1269 #endif /* !PRODUCT */