1 /*
   2  * Copyright (c) 2001, 2014, 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_implementation/shared/adaptiveSizePolicy.hpp"
  27 #include "gc_implementation/shared/gcPolicyCounters.hpp"
  28 #include "gc_implementation/shared/vmGCOperations.hpp"
  29 #include "memory/cardTableRS.hpp"
  30 #include "memory/collectorPolicy.hpp"
  31 #include "memory/gcLocker.inline.hpp"
  32 #include "memory/genCollectedHeap.hpp"
  33 #include "memory/generationSpec.hpp"
  34 #include "memory/space.hpp"
  35 #include "memory/universe.hpp"
  36 #include "runtime/arguments.hpp"
  37 #include "runtime/globals_extension.hpp"
  38 #include "runtime/handles.inline.hpp"
  39 #include "runtime/java.hpp"
  40 #include "runtime/thread.inline.hpp"
  41 #include "runtime/vmThread.hpp"
  42 #include "utilities/macros.hpp"
  43 #if INCLUDE_ALL_GCS
  44 #include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
  45 #include "gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp"
  46 #endif // INCLUDE_ALL_GCS
  47 
  48 // CollectorPolicy methods
  49 
  50 CollectorPolicy::CollectorPolicy() :
  51     _space_alignment(0),
  52     _heap_alignment(0),
  53     _initial_heap_byte_size(InitialHeapSize),
  54     _max_heap_byte_size(MaxHeapSize),
  55     _min_heap_byte_size(Arguments::min_heap_size()),
  56     _max_heap_size_cmdline(false),
  57     _size_policy(NULL),
  58     _should_clear_all_soft_refs(false),
  59     _all_soft_refs_clear(false)
  60 {}
  61 
  62 #ifdef ASSERT
  63 void CollectorPolicy::assert_flags() {
  64   assert(InitialHeapSize <= MaxHeapSize, "Ergonomics decided on incompatible initial and maximum heap sizes");
  65   assert(InitialHeapSize % _heap_alignment == 0, "InitialHeapSize alignment");
  66   assert(MaxHeapSize % _heap_alignment == 0, "MaxHeapSize alignment");
  67 }
  68 
  69 void CollectorPolicy::assert_size_info() {
  70   assert(InitialHeapSize == _initial_heap_byte_size, "Discrepancy between InitialHeapSize flag and local storage");
  71   assert(MaxHeapSize == _max_heap_byte_size, "Discrepancy between MaxHeapSize flag and local storage");
  72   assert(_max_heap_byte_size >= _min_heap_byte_size, "Ergonomics decided on incompatible minimum and maximum heap sizes");
  73   assert(_initial_heap_byte_size >= _min_heap_byte_size, "Ergonomics decided on incompatible initial and minimum heap sizes");
  74   assert(_max_heap_byte_size >= _initial_heap_byte_size, "Ergonomics decided on incompatible initial and maximum heap sizes");
  75   assert(_min_heap_byte_size % _heap_alignment == 0, "min_heap_byte_size alignment");
  76   assert(_initial_heap_byte_size % _heap_alignment == 0, "initial_heap_byte_size alignment");
  77   assert(_max_heap_byte_size % _heap_alignment == 0, "max_heap_byte_size alignment");
  78 }
  79 #endif // ASSERT
  80 
  81 void CollectorPolicy::initialize_flags() {
  82   assert(_space_alignment != 0, "Space alignment not set up properly");
  83   assert(_heap_alignment != 0, "Heap alignment not set up properly");
  84   assert(_heap_alignment >= _space_alignment,
  85          err_msg("heap_alignment: " SIZE_FORMAT " less than space_alignment: " SIZE_FORMAT,
  86                  _heap_alignment, _space_alignment));
  87   assert(_heap_alignment % _space_alignment == 0,
  88          err_msg("heap_alignment: " SIZE_FORMAT " not aligned by space_alignment: " SIZE_FORMAT,
  89                  _heap_alignment, _space_alignment));
  90 
  91   if (FLAG_IS_CMDLINE(MaxHeapSize)) {
  92     if (FLAG_IS_CMDLINE(InitialHeapSize) && InitialHeapSize > MaxHeapSize) {
  93       vm_exit_during_initialization("Initial heap size set to a larger value than the maximum heap size");
  94     }
  95     if (_min_heap_byte_size != 0 && MaxHeapSize < _min_heap_byte_size) {
  96       vm_exit_during_initialization("Incompatible minimum and maximum heap sizes specified");
  97     }
  98     _max_heap_size_cmdline = true;
  99   }
 100 
 101   // Check heap parameter properties
 102   if (InitialHeapSize < M) {
 103     vm_exit_during_initialization("Too small initial heap");
 104   }
 105   if (_min_heap_byte_size < M) {
 106     vm_exit_during_initialization("Too small minimum heap");
 107   }
 108 
 109   // User inputs from -Xmx and -Xms must be aligned
 110   _min_heap_byte_size = align_size_up(_min_heap_byte_size, _heap_alignment);
 111   uintx aligned_initial_heap_size = align_size_up(InitialHeapSize, _heap_alignment);
 112   uintx aligned_max_heap_size = align_size_up(MaxHeapSize, _heap_alignment);
 113 
 114   // Write back to flags if the values changed
 115   if (aligned_initial_heap_size != InitialHeapSize) {
 116     FLAG_SET_ERGO(uintx, InitialHeapSize, aligned_initial_heap_size);
 117   }
 118   if (aligned_max_heap_size != MaxHeapSize) {
 119     FLAG_SET_ERGO(uintx, MaxHeapSize, aligned_max_heap_size);
 120   }
 121 
 122   if (FLAG_IS_CMDLINE(InitialHeapSize) && _min_heap_byte_size != 0 &&
 123       InitialHeapSize < _min_heap_byte_size) {
 124     vm_exit_during_initialization("Incompatible minimum and initial heap sizes specified");
 125   }
 126   if (!FLAG_IS_DEFAULT(InitialHeapSize) && InitialHeapSize > MaxHeapSize) {
 127     FLAG_SET_ERGO(uintx, MaxHeapSize, InitialHeapSize);
 128   } else if (!FLAG_IS_DEFAULT(MaxHeapSize) && InitialHeapSize > MaxHeapSize) {
 129     FLAG_SET_ERGO(uintx, InitialHeapSize, MaxHeapSize);
 130     if (InitialHeapSize < _min_heap_byte_size) {
 131       _min_heap_byte_size = InitialHeapSize;
 132     }
 133   }
 134 
 135   _initial_heap_byte_size = InitialHeapSize;
 136   _max_heap_byte_size = MaxHeapSize;
 137 
 138   FLAG_SET_ERGO(uintx, MinHeapDeltaBytes, align_size_up(MinHeapDeltaBytes, _space_alignment));
 139 
 140   DEBUG_ONLY(CollectorPolicy::assert_flags();)
 141 }
 142 
 143 void CollectorPolicy::initialize_size_info() {
 144   if (PrintGCDetails && Verbose) {
 145     gclog_or_tty->print_cr("Minimum heap " SIZE_FORMAT "  Initial heap "
 146       SIZE_FORMAT "  Maximum heap " SIZE_FORMAT,
 147       _min_heap_byte_size, _initial_heap_byte_size, _max_heap_byte_size);
 148   }
 149 
 150   DEBUG_ONLY(CollectorPolicy::assert_size_info();)
 151 }
 152 
 153 bool CollectorPolicy::use_should_clear_all_soft_refs(bool v) {
 154   bool result = _should_clear_all_soft_refs;
 155   set_should_clear_all_soft_refs(false);
 156   return result;
 157 }
 158 
 159 GenRemSet* CollectorPolicy::create_rem_set(MemRegion whole_heap,
 160                                            int max_covered_regions) {
 161   return new CardTableRS(whole_heap, max_covered_regions);
 162 }
 163 
 164 void CollectorPolicy::cleared_all_soft_refs() {
 165   // If near gc overhear limit, continue to clear SoftRefs.  SoftRefs may
 166   // have been cleared in the last collection but if the gc overhear
 167   // limit continues to be near, SoftRefs should still be cleared.
 168   if (size_policy() != NULL) {
 169     _should_clear_all_soft_refs = size_policy()->gc_overhead_limit_near();
 170   }
 171   _all_soft_refs_clear = true;
 172 }
 173 
 174 size_t CollectorPolicy::compute_heap_alignment() {
 175   // The card marking array and the offset arrays for old generations are
 176   // committed in os pages as well. Make sure they are entirely full (to
 177   // avoid partial page problems), e.g. if 512 bytes heap corresponds to 1
 178   // byte entry and the os page size is 4096, the maximum heap size should
 179   // be 512*4096 = 2MB aligned.
 180 
 181   size_t alignment = GenRemSet::max_alignment_constraint();
 182 
 183   // Parallel GC does its own alignment of the generations to avoid requiring a
 184   // large page (256M on some platforms) for the permanent generation.  The
 185   // other collectors should also be updated to do their own alignment and then
 186   // this use of lcm() should be removed.
 187   if (UseLargePages && !UseParallelGC) {
 188       // In presence of large pages we have to make sure that our
 189       // alignment is large page aware
 190       alignment = lcm(os::large_page_size(), alignment);
 191   }
 192 
 193   return alignment;
 194 }
 195 
 196 // GenCollectorPolicy methods
 197 
 198 GenCollectorPolicy::GenCollectorPolicy() :
 199     _min_gen0_size(0),
 200     _initial_gen0_size(0),
 201     _max_gen0_size(0),
 202     _gen_alignment(0),
 203     _min_gen1_size(0),
 204     _initial_gen1_size(0),
 205     _max_gen1_size(0),
 206     _generations(NULL)
 207 {}
 208 
 209 size_t GenCollectorPolicy::scale_by_NewRatio_aligned(size_t base_size) {
 210   return align_size_down_bounded(base_size / (NewRatio + 1), _gen_alignment);
 211 }
 212 
 213 size_t GenCollectorPolicy::bound_minus_alignment(size_t desired_size,
 214                                                  size_t maximum_size) {
 215   size_t max_minus = maximum_size - _gen_alignment;
 216   return desired_size < max_minus ? desired_size : max_minus;
 217 }
 218 
 219 
 220 void GenCollectorPolicy::initialize_size_policy(size_t init_eden_size,
 221                                                 size_t init_promo_size,
 222                                                 size_t init_survivor_size) {
 223   const double max_gc_pause_sec = ((double) MaxGCPauseMillis) / 1000.0;
 224   _size_policy = new AdaptiveSizePolicy(init_eden_size,
 225                                         init_promo_size,
 226                                         init_survivor_size,
 227                                         max_gc_pause_sec,
 228                                         GCTimeRatio);
 229 }
 230 
 231 size_t GenCollectorPolicy::young_gen_size_lower_bound() {
 232   // The young generation must be aligned and have room for eden + two survivors
 233   return align_size_up(3 * _space_alignment, _gen_alignment);
 234 }
 235 
 236 #ifdef ASSERT
 237 void GenCollectorPolicy::assert_flags() {
 238   CollectorPolicy::assert_flags();
 239   assert(NewSize >= _min_gen0_size, "Ergonomics decided on a too small young gen size");
 240   assert(NewSize <= MaxNewSize, "Ergonomics decided on incompatible initial and maximum young gen sizes");
 241   assert(FLAG_IS_DEFAULT(MaxNewSize) || MaxNewSize < MaxHeapSize, "Ergonomics decided on incompatible maximum young gen and heap sizes");
 242   assert(NewSize % _gen_alignment == 0, "NewSize alignment");
 243   assert(FLAG_IS_DEFAULT(MaxNewSize) || MaxNewSize % _gen_alignment == 0, "MaxNewSize alignment");
 244   assert(OldSize + NewSize <= MaxHeapSize, "Ergonomics decided on incompatible generation and heap sizes");
 245   assert(OldSize % _gen_alignment == 0, "OldSize alignment");
 246 }
 247 
 248 void GenCollectorPolicy::assert_size_info() {
 249   CollectorPolicy::assert_size_info();
 250   // GenCollectorPolicy::initialize_size_info may update the MaxNewSize
 251   assert(MaxNewSize < MaxHeapSize, "Ergonomics decided on incompatible maximum young and heap sizes");
 252   assert(NewSize == _initial_gen0_size, "Discrepancy between NewSize flag and local storage");
 253   assert(MaxNewSize == _max_gen0_size, "Discrepancy between MaxNewSize flag and local storage");
 254   assert(OldSize == _initial_gen1_size, "Discrepancy between OldSize flag and local storage");
 255   assert(_min_gen0_size <= _initial_gen0_size, "Ergonomics decided on incompatible minimum and initial young gen sizes");
 256   assert(_initial_gen0_size <= _max_gen0_size, "Ergonomics decided on incompatible initial and maximum young gen sizes");
 257   assert(_min_gen0_size % _gen_alignment == 0, "_min_gen0_size alignment");
 258   assert(_initial_gen0_size % _gen_alignment == 0, "_initial_gen0_size alignment");
 259   assert(_max_gen0_size % _gen_alignment == 0, "_max_gen0_size alignment");
 260   assert(_min_gen0_size <= bound_minus_alignment(_min_gen0_size, _min_heap_byte_size),
 261       "Ergonomics made minimum young generation larger than minimum heap");
 262   assert(_initial_gen0_size <=  bound_minus_alignment(_initial_gen0_size, _initial_heap_byte_size),
 263       "Ergonomics made initial young generation larger than initial heap");
 264   assert(_max_gen0_size <= bound_minus_alignment(_max_gen0_size, _max_heap_byte_size),
 265       "Ergonomics made maximum young generation lager than maximum heap");
 266   assert(_min_gen1_size <= _initial_gen1_size, "Ergonomics decided on incompatible minimum and initial old gen sizes");
 267   assert(_initial_gen1_size <= _max_gen1_size, "Ergonomics decided on incompatible initial and maximum old gen sizes");
 268   assert(_max_gen1_size % _gen_alignment == 0, "_max_gen1_size alignment");
 269   assert(_initial_gen1_size % _gen_alignment == 0, "_initial_gen1_size alignment");
 270   assert(_max_heap_byte_size <= (_max_gen0_size + _max_gen1_size), "Total maximum heap sizes must be sum of generation maximum sizes");
 271   assert(_min_gen0_size + _min_gen1_size <= _min_heap_byte_size, "Minimum generation sizes exceed minimum heap size");
 272   assert(_initial_gen0_size + _initial_gen1_size == _initial_heap_byte_size, "Initial generation sizes should match initial heap size");
 273   assert(_max_gen0_size + _max_gen1_size == _max_heap_byte_size, "Maximum generation sizes should match maximum heap size");
 274 }
 275 #endif // ASSERT
 276 
 277 void GenCollectorPolicy::initialize_flags() {
 278   CollectorPolicy::initialize_flags();
 279 
 280   assert(_gen_alignment != 0, "Generation alignment not set up properly");
 281   assert(_heap_alignment >= _gen_alignment,
 282          err_msg("heap_alignment: " SIZE_FORMAT " less than gen_alignment: " SIZE_FORMAT,
 283                  _heap_alignment, _gen_alignment));
 284   assert(_gen_alignment % _space_alignment == 0,
 285          err_msg("gen_alignment: " SIZE_FORMAT " not aligned by space_alignment: " SIZE_FORMAT,
 286                  _gen_alignment, _space_alignment));
 287   assert(_heap_alignment % _gen_alignment == 0,
 288          err_msg("heap_alignment: " SIZE_FORMAT " not aligned by gen_alignment: " SIZE_FORMAT,
 289                  _heap_alignment, _gen_alignment));
 290 
 291   // All generational heaps have a youngest gen; handle those flags here
 292 
 293   // Make sure the heap is large enough for two generations
 294   uintx smallest_new_size = young_gen_size_lower_bound();
 295   uintx smallest_heap_size = align_size_up(smallest_new_size + align_size_up(_space_alignment, _gen_alignment),
 296                                            _heap_alignment);
 297   if (MaxHeapSize < smallest_heap_size) {
 298     FLAG_SET_ERGO(uintx, MaxHeapSize, smallest_heap_size);
 299     _max_heap_byte_size = MaxHeapSize;
 300   }
 301   // If needed, synchronize _min_heap_byte size and _initial_heap_byte_size
 302   if (_min_heap_byte_size < smallest_heap_size) {
 303     _min_heap_byte_size = smallest_heap_size;
 304     if (InitialHeapSize < _min_heap_byte_size) {
 305       FLAG_SET_ERGO(uintx, InitialHeapSize, smallest_heap_size);
 306       _initial_heap_byte_size = smallest_heap_size;
 307     }
 308   }
 309 
 310   // Make sure NewSize allows an old generation to fit even if set on the command line
 311   if (FLAG_IS_CMDLINE(NewSize) && NewSize >= _initial_heap_byte_size) {
 312     warning("NewSize was set larger than initial heap size, will use initial heap size.");
 313     NewSize = bound_minus_alignment(NewSize, _initial_heap_byte_size);
 314   }
 315 
 316   // Now take the actual NewSize into account. We will silently increase NewSize
 317   // if the user specified a smaller or unaligned value.
 318   uintx bounded_new_size = bound_minus_alignment(NewSize, MaxHeapSize);
 319   bounded_new_size = MAX2(smallest_new_size, (uintx)align_size_down(bounded_new_size, _gen_alignment));
 320   if (bounded_new_size != NewSize) {
 321     // Do not use FLAG_SET_ERGO to update NewSize here, since this will override
 322     // if NewSize was set on the command line or not. This information is needed
 323     // later when setting the initial and minimum young generation size.
 324     NewSize = bounded_new_size;
 325   }
 326   _min_gen0_size = smallest_new_size;
 327   _initial_gen0_size = NewSize;
 328 
 329   if (!FLAG_IS_DEFAULT(MaxNewSize)) {
 330     if (MaxNewSize >= MaxHeapSize) {
 331       // Make sure there is room for an old generation
 332       uintx smaller_max_new_size = MaxHeapSize - _gen_alignment;
 333       if (FLAG_IS_CMDLINE(MaxNewSize)) {
 334         warning("MaxNewSize (" SIZE_FORMAT "k) is equal to or greater than the entire "
 335                 "heap (" SIZE_FORMAT "k).  A new max generation size of " SIZE_FORMAT "k will be used.",
 336                 MaxNewSize/K, MaxHeapSize/K, smaller_max_new_size/K);
 337       }
 338       FLAG_SET_ERGO(uintx, MaxNewSize, smaller_max_new_size);
 339       if (NewSize > MaxNewSize) {
 340         FLAG_SET_ERGO(uintx, NewSize, MaxNewSize);
 341         _initial_gen0_size = NewSize;
 342       }
 343     } else if (MaxNewSize < _initial_gen0_size) {
 344       FLAG_SET_ERGO(uintx, MaxNewSize, _initial_gen0_size);
 345     } else if (!is_size_aligned(MaxNewSize, _gen_alignment)) {
 346       FLAG_SET_ERGO(uintx, MaxNewSize, align_size_down(MaxNewSize, _gen_alignment));
 347     }
 348     _max_gen0_size = MaxNewSize;
 349   }
 350 
 351   if (NewSize > MaxNewSize) {
 352     // At this point this should only happen if the user specifies a large NewSize and/or
 353     // a small (but not too small) MaxNewSize.
 354     if (FLAG_IS_CMDLINE(MaxNewSize)) {
 355       warning("NewSize (" SIZE_FORMAT "k) is greater than the MaxNewSize (" SIZE_FORMAT "k). "
 356               "A new max generation size of " SIZE_FORMAT "k will be used.",
 357               NewSize/K, MaxNewSize/K, NewSize/K);
 358     }
 359     FLAG_SET_ERGO(uintx, MaxNewSize, NewSize);
 360     _max_gen0_size = MaxNewSize;
 361   }
 362 
 363   if (SurvivorRatio < 1 || NewRatio < 1) {
 364     vm_exit_during_initialization("Invalid young gen ratio specified");
 365   }
 366 
 367   if (!is_size_aligned(OldSize, _gen_alignment)) {
 368     // Setting OldSize directly to preserve information about the possible
 369     // setting of OldSize on the command line.
 370     OldSize = align_size_down(OldSize, _gen_alignment);
 371   }
 372 
 373   if (FLAG_IS_CMDLINE(OldSize) && FLAG_IS_DEFAULT(MaxHeapSize)) {
 374     // NewRatio will be used later to set the young generation size so we use
 375     // it to calculate how big the heap should be based on the requested OldSize
 376     // and NewRatio.
 377     assert(NewRatio > 0, "NewRatio should have been set up earlier");
 378     size_t calculated_heapsize = (OldSize / NewRatio) * (NewRatio + 1);
 379 
 380     calculated_heapsize = align_size_up(calculated_heapsize, _heap_alignment);
 381     FLAG_SET_ERGO(uintx, MaxHeapSize, calculated_heapsize);
 382     _max_heap_byte_size = MaxHeapSize;
 383     FLAG_SET_ERGO(uintx, InitialHeapSize, calculated_heapsize);
 384     _initial_heap_byte_size = InitialHeapSize;
 385   }
 386 
 387   // Adjust NewSize and OldSize or MaxHeapSize to match each other
 388   if (NewSize + OldSize > MaxHeapSize) {
 389     if (_max_heap_size_cmdline) {
 390       // Somebody has set a maximum heap size with the intention that we should not
 391       // exceed it. Adjust New/OldSize as necessary.
 392       uintx calculated_size = NewSize + OldSize;
 393       double shrink_factor = (double) MaxHeapSize / calculated_size;
 394       uintx smaller_new_size = align_size_down((uintx)(NewSize * shrink_factor), _gen_alignment);
 395       FLAG_SET_ERGO(uintx, NewSize, MAX2(young_gen_size_lower_bound(), (size_t)smaller_new_size));
 396       _initial_gen0_size = NewSize;
 397 
 398       // OldSize is already aligned because above we aligned MaxHeapSize to
 399       // _heap_alignment, and we just made sure that NewSize is aligned to
 400       // _gen_alignment. In initialize_flags() we verified that _heap_alignment
 401       // is a multiple of _gen_alignment.
 402       FLAG_SET_ERGO(uintx, OldSize, MaxHeapSize - NewSize);
 403     } else {
 404       FLAG_SET_ERGO(uintx, MaxHeapSize, align_size_up(NewSize + OldSize, _heap_alignment));
 405       _max_heap_byte_size = MaxHeapSize;
 406     }
 407   }
 408 
 409   // Update NewSize, if possible, to avoid sizing gen0 to small when only
 410   // OldSize is set on the command line.
 411   if (FLAG_IS_CMDLINE(OldSize) && !FLAG_IS_CMDLINE(NewSize)) {
 412     if (OldSize < _initial_heap_byte_size) {
 413       size_t new_size = _initial_heap_byte_size - OldSize;
 414       // Need to compare against the flag value for max since _max_gen0_size
 415       // might not have been set yet.
 416       if (new_size >= _min_gen0_size && new_size <= MaxNewSize) {
 417         FLAG_SET_ERGO(uintx, NewSize, new_size);
 418         _initial_gen0_size = NewSize;
 419       }
 420     }
 421   }
 422 
 423   always_do_update_barrier = UseConcMarkSweepGC;
 424 
 425   DEBUG_ONLY(GenCollectorPolicy::assert_flags();)
 426 }
 427 
 428 // Values set on the command line win over any ergonomically
 429 // set command line parameters.
 430 // Ergonomic choice of parameters are done before this
 431 // method is called.  Values for command line parameters such as NewSize
 432 // and MaxNewSize feed those ergonomic choices into this method.
 433 // This method makes the final generation sizings consistent with
 434 // themselves and with overall heap sizings.
 435 // In the absence of explicitly set command line flags, policies
 436 // such as the use of NewRatio are used to size the generation.
 437 
 438 // Minimum sizes of the generations may be different than
 439 // the initial sizes.  An inconsistency is permitted here
 440 // in the total size that can be specified explicitly by
 441 // command line specification of OldSize and NewSize and
 442 // also a command line specification of -Xms.  Issue a warning
 443 // but allow the values to pass.
 444 void GenCollectorPolicy::initialize_size_info() {
 445   CollectorPolicy::initialize_size_info();
 446 
 447   // _space_alignment is used for alignment within a generation.
 448   // There is additional alignment done down stream for some
 449   // collectors that sometimes causes unwanted rounding up of
 450   // generations sizes.
 451 
 452   // Determine maximum size of gen0
 453 
 454   size_t max_new_size = 0;
 455   if (!FLAG_IS_DEFAULT(MaxNewSize)) {
 456     max_new_size = MaxNewSize;
 457   } else {
 458     max_new_size = scale_by_NewRatio_aligned(_max_heap_byte_size);
 459     // Bound the maximum size by NewSize below (since it historically
 460     // would have been NewSize and because the NewRatio calculation could
 461     // yield a size that is too small) and bound it by MaxNewSize above.
 462     // Ergonomics plays here by previously calculating the desired
 463     // NewSize and MaxNewSize.
 464     max_new_size = MIN2(MAX2(max_new_size, (size_t)NewSize), (size_t)MaxNewSize);
 465   }
 466   assert(max_new_size > 0, "All paths should set max_new_size");
 467 
 468   // Given the maximum gen0 size, determine the initial and
 469   // minimum gen0 sizes.
 470 
 471   if (_max_heap_byte_size == _initial_heap_byte_size) {
 472     // The maxium and initial heap sizes are the same so the generation's
 473     // initial size must be the same as it maximum size. Use NewSize as the
 474     // size if set on command line.
 475     size_t fixed_young_size = FLAG_IS_CMDLINE(NewSize) ? NewSize : max_new_size;
 476 
 477     _initial_gen0_size = fixed_young_size;
 478     _max_gen0_size = fixed_young_size;
 479 
 480     // Also update the minimum size if min == initial == max.
 481     if (_max_heap_byte_size == _min_heap_byte_size) {
 482       _min_gen0_size = fixed_young_size;
 483     }
 484   } else {
 485     size_t desired_new_size = 0;
 486     if (FLAG_IS_CMDLINE(NewSize)) {
 487       // If NewSize is set on the command line, we should use it as
 488       // the initial size, but make sure it is within the heap bounds.
 489       desired_new_size =
 490         MIN2(max_new_size, bound_minus_alignment(NewSize, _initial_heap_byte_size));
 491       _min_gen0_size = bound_minus_alignment(desired_new_size, _min_heap_byte_size);
 492     } else {
 493       // For the case where NewSize is not set on the command line, use
 494       // NewRatio to size the initial generation size. Use the current
 495       // NewSize as the floor, because if NewRatio is overly large, the resulting
 496       // size can be too small.
 497       desired_new_size =
 498         MIN2(max_new_size, MAX2(scale_by_NewRatio_aligned(_initial_heap_byte_size), (size_t)NewSize));
 499     }
 500     _initial_gen0_size = desired_new_size;
 501     _max_gen0_size = max_new_size;
 502   }
 503 
 504   // Write back to flags if necessary.
 505   if (NewSize != _initial_gen0_size) {
 506     FLAG_SET_ERGO(uintx, NewSize, _initial_gen0_size);
 507   }
 508 
 509   if (MaxNewSize != _max_gen0_size) {
 510     FLAG_SET_ERGO(uintx, MaxNewSize, _max_gen0_size);
 511   }
 512 
 513   if (PrintGCDetails && Verbose) {
 514     gclog_or_tty->print_cr("1: Minimum gen0 " SIZE_FORMAT "  Initial gen0 "
 515       SIZE_FORMAT "  Maximum gen0 " SIZE_FORMAT,
 516       _min_gen0_size, _initial_gen0_size, _max_gen0_size);
 517   }
 518 
 519   // At this point the minimum, initial and maximum sizes
 520   // of the overall heap and of gen0 have been determined.
 521   // The maximum gen1 size can be determined from the maximum gen0
 522   // and maximum heap size since no explicit flags exist
 523   // for setting the gen1 maximum.
 524   _max_gen1_size = MAX2(_max_heap_byte_size - _max_gen0_size, _gen_alignment);
 525 
 526   // If no explicit command line flag has been set for the
 527   // gen1 size, use what is left for gen1
 528   if (!FLAG_IS_CMDLINE(OldSize)) {
 529     // The user has not specified any value but the ergonomics
 530     // may have chosen a value (which may or may not be consistent
 531     // with the overall heap size).  In either case make
 532     // the minimum, maximum and initial sizes consistent
 533     // with the gen0 sizes and the overall heap sizes.
 534     _min_gen1_size = _gen_alignment;
 535     _initial_gen1_size = MIN2(_max_gen1_size, MAX2(_initial_heap_byte_size - _initial_gen0_size, _min_gen1_size));
 536     // _max_gen1_size has already been made consistent above
 537     FLAG_SET_ERGO(uintx, OldSize, _initial_gen1_size);
 538   } else {
 539     // OldSize has been explicitly set on the command line. Use it
 540     // for the initial size but make sure the minimum allow a young
 541     // generation to fit as well.
 542     // If the user has explicitly set an OldSize that is inconsistent
 543     // with other command line flags, issue a warning.
 544     // The generation minimums and the overall heap minimum should
 545     // be within one generation alignment.
 546     if (OldSize > _max_gen1_size) {
 547       warning("Inconsistency between maximum heap size and maximum "
 548           "generation sizes: using maximum heap = " SIZE_FORMAT
 549           " -XX:OldSize flag is being ignored",
 550           _max_heap_byte_size);
 551       FLAG_SET_ERGO(uintx, OldSize, _max_gen1_size);
 552     }
 553 
 554     _min_gen1_size = MIN2((size_t)OldSize, _min_heap_byte_size - _min_gen0_size);
 555     _initial_gen1_size = OldSize;
 556   }
 557 
 558   // The initial generation sizes should match the initial heap size,
 559   // if not issue a warning and resize the generations. This behavior
 560   // differs from JDK8 where the generation sizes have higher priority
 561   // than the initial heap size.
 562   if ((_initial_gen1_size + _initial_gen0_size) != _initial_heap_byte_size) {
 563     warning("Inconsistency between generation sizes and heap size, resizing "
 564             "the generations to fit the heap.");
 565 
 566     size_t desired_gen0_size = _initial_heap_byte_size - _initial_gen1_size;
 567     if (_initial_heap_byte_size < _initial_gen1_size) {
 568       // Old want all memory, use minimum for young and rest for old
 569       _initial_gen0_size = _min_gen0_size;
 570       _initial_gen1_size = _initial_heap_byte_size - _min_gen0_size;
 571     } else if (desired_gen0_size > _max_gen0_size) {
 572       // Need to increase both young and old generation
 573       _initial_gen0_size = _max_gen0_size;
 574       _initial_gen1_size = _initial_heap_byte_size - _max_gen0_size;
 575     } else if (desired_gen0_size < _min_gen0_size) {
 576       // Need to decrease both young and old generation
 577       _initial_gen0_size = _min_gen0_size;
 578       _initial_gen1_size = _initial_heap_byte_size - _min_gen0_size;
 579     } else {
 580       // The young generation boundaries allow us to only update the
 581       // young generation.
 582       _initial_gen0_size = desired_gen0_size;
 583     }
 584 
 585     if (PrintGCDetails && Verbose) {
 586       gclog_or_tty->print_cr("2: Minimum gen0 " SIZE_FORMAT "  Initial gen0 "
 587         SIZE_FORMAT "  Maximum gen0 " SIZE_FORMAT,
 588         _min_gen0_size, _initial_gen0_size, _max_gen0_size);
 589     }
 590   }
 591 
 592   // Write back to flags if necessary
 593   if (NewSize != _initial_gen0_size) {
 594     FLAG_SET_ERGO(uintx, NewSize, _initial_gen0_size);
 595   }
 596 
 597   if (MaxNewSize != _max_gen0_size) {
 598     FLAG_SET_ERGO(uintx, MaxNewSize, _max_gen0_size);
 599   }
 600 
 601   if (OldSize != _initial_gen1_size) {
 602     FLAG_SET_ERGO(uintx, OldSize, _initial_gen1_size);
 603   }
 604 
 605   if (PrintGCDetails && Verbose) {
 606     gclog_or_tty->print_cr("Minimum gen1 " SIZE_FORMAT "  Initial gen1 "
 607       SIZE_FORMAT "  Maximum gen1 " SIZE_FORMAT,
 608       _min_gen1_size, _initial_gen1_size, _max_gen1_size);
 609   }
 610 
 611   DEBUG_ONLY(GenCollectorPolicy::assert_size_info();)
 612 }
 613 
 614 HeapWord* GenCollectorPolicy::mem_allocate_work(size_t size,
 615                                         bool is_tlab,
 616                                         bool* gc_overhead_limit_was_exceeded) {
 617   GenCollectedHeap *gch = GenCollectedHeap::heap();
 618 
 619   debug_only(gch->check_for_valid_allocation_state());
 620   assert(gch->no_gc_in_progress(), "Allocation during gc not allowed");
 621 
 622   // In general gc_overhead_limit_was_exceeded should be false so
 623   // set it so here and reset it to true only if the gc time
 624   // limit is being exceeded as checked below.
 625   *gc_overhead_limit_was_exceeded = false;
 626 
 627   HeapWord* result = NULL;
 628 
 629   // Loop until the allocation is satisfied, or unsatisfied after GC.
 630   for (int try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) {
 631     HandleMark hm; // Discard any handles allocated in each iteration.
 632 
 633     // First allocation attempt is lock-free.
 634     Generation *gen0 = gch->get_gen(0);
 635     assert(gen0->supports_inline_contig_alloc(),
 636       "Otherwise, must do alloc within heap lock");
 637     if (gen0->should_allocate(size, is_tlab)) {
 638       result = gen0->par_allocate(size, is_tlab);
 639       if (result != NULL) {
 640         assert(gch->is_in_reserved(result), "result not in heap");
 641         return result;
 642       }
 643     }
 644     unsigned int gc_count_before;  // Read inside the Heap_lock locked region.
 645     {
 646       MutexLocker ml(Heap_lock);
 647       if (PrintGC && Verbose) {
 648         gclog_or_tty->print_cr("TwoGenerationCollectorPolicy::mem_allocate_work:"
 649                       " attempting locked slow path allocation");
 650       }
 651       // Note that only large objects get a shot at being
 652       // allocated in later generations.
 653       bool first_only = ! should_try_older_generation_allocation(size);
 654 
 655       result = gch->attempt_allocation(size, is_tlab, first_only);
 656       if (result != NULL) {
 657         assert(gch->is_in_reserved(result), "result not in heap");
 658         return result;
 659       }
 660 
 661       if (GC_locker::is_active_and_needs_gc()) {
 662         if (is_tlab) {
 663           return NULL;  // Caller will retry allocating individual object.
 664         }
 665         if (!gch->is_maximal_no_gc()) {
 666           // Try and expand heap to satisfy request.
 667           result = expand_heap_and_allocate(size, is_tlab);
 668           // Result could be null if we are out of space.
 669           if (result != NULL) {
 670             return result;
 671           }
 672         }
 673 
 674         if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
 675           return NULL; // We didn't get to do a GC and we didn't get any memory.
 676         }
 677 
 678         // If this thread is not in a jni critical section, we stall
 679         // the requestor until the critical section has cleared and
 680         // GC allowed. When the critical section clears, a GC is
 681         // initiated by the last thread exiting the critical section; so
 682         // we retry the allocation sequence from the beginning of the loop,
 683         // rather than causing more, now probably unnecessary, GC attempts.
 684         JavaThread* jthr = JavaThread::current();
 685         if (!jthr->in_critical()) {
 686           MutexUnlocker mul(Heap_lock);
 687           // Wait for JNI critical section to be exited
 688           GC_locker::stall_until_clear();
 689           gclocker_stalled_count += 1;
 690           continue;
 691         } else {
 692           if (CheckJNICalls) {
 693             fatal("Possible deadlock due to allocating while"
 694                   " in jni critical section");
 695           }
 696           return NULL;
 697         }
 698       }
 699 
 700       // Read the gc count while the heap lock is held.
 701       gc_count_before = Universe::heap()->total_collections();
 702     }
 703 
 704     VM_GenCollectForAllocation op(size, is_tlab, gc_count_before);
 705     VMThread::execute(&op);
 706     if (op.prologue_succeeded()) {
 707       result = op.result();
 708       if (op.gc_locked()) {
 709          assert(result == NULL, "must be NULL if gc_locked() is true");
 710          continue;  // Retry and/or stall as necessary.
 711       }
 712 
 713       // Allocation has failed and a collection
 714       // has been done.  If the gc time limit was exceeded the
 715       // this time, return NULL so that an out-of-memory
 716       // will be thrown.  Clear gc_overhead_limit_exceeded
 717       // so that the overhead exceeded does not persist.
 718 
 719       const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
 720       const bool softrefs_clear = all_soft_refs_clear();
 721 
 722       if (limit_exceeded && softrefs_clear) {
 723         *gc_overhead_limit_was_exceeded = true;
 724         size_policy()->set_gc_overhead_limit_exceeded(false);
 725         if (op.result() != NULL) {
 726           CollectedHeap::fill_with_object(op.result(), size);
 727         }
 728         return NULL;
 729       }
 730       assert(result == NULL || gch->is_in_reserved(result),
 731              "result not in heap");
 732       return result;
 733     }
 734 
 735     // Give a warning if we seem to be looping forever.
 736     if ((QueuedAllocationWarningCount > 0) &&
 737         (try_count % QueuedAllocationWarningCount == 0)) {
 738           warning("TwoGenerationCollectorPolicy::mem_allocate_work retries %d times \n\t"
 739                   " size=" SIZE_FORMAT " %s", try_count, size, is_tlab ? "(TLAB)" : "");
 740     }
 741   }
 742 }
 743 
 744 HeapWord* GenCollectorPolicy::expand_heap_and_allocate(size_t size,
 745                                                        bool   is_tlab) {
 746   GenCollectedHeap *gch = GenCollectedHeap::heap();
 747   HeapWord* result = NULL;
 748   for (int i = number_of_generations() - 1; i >= 0 && result == NULL; i--) {
 749     Generation *gen = gch->get_gen(i);
 750     if (gen->should_allocate(size, is_tlab)) {
 751       result = gen->expand_and_allocate(size, is_tlab);
 752     }
 753   }
 754   assert(result == NULL || gch->is_in_reserved(result), "result not in heap");
 755   return result;
 756 }
 757 
 758 HeapWord* GenCollectorPolicy::satisfy_failed_allocation(size_t size,
 759                                                         bool   is_tlab) {
 760   GenCollectedHeap *gch = GenCollectedHeap::heap();
 761   GCCauseSetter x(gch, GCCause::_allocation_failure);
 762   HeapWord* result = NULL;
 763 
 764   assert(size != 0, "Precondition violated");
 765   if (GC_locker::is_active_and_needs_gc()) {
 766     // GC locker is active; instead of a collection we will attempt
 767     // to expand the heap, if there's room for expansion.
 768     if (!gch->is_maximal_no_gc()) {
 769       result = expand_heap_and_allocate(size, is_tlab);
 770     }
 771     return result;   // Could be null if we are out of space.
 772   } else if (!gch->incremental_collection_will_fail(false /* don't consult_young */)) {
 773     // Do an incremental collection.
 774     gch->do_collection(false            /* full */,
 775                        false            /* clear_all_soft_refs */,
 776                        size             /* size */,
 777                        is_tlab          /* is_tlab */,
 778                        number_of_generations() - 1 /* max_level */);
 779   } else {
 780     if (Verbose && PrintGCDetails) {
 781       gclog_or_tty->print(" :: Trying full because partial may fail :: ");
 782     }
 783     // Try a full collection; see delta for bug id 6266275
 784     // for the original code and why this has been simplified
 785     // with from-space allocation criteria modified and
 786     // such allocation moved out of the safepoint path.
 787     gch->do_collection(true             /* full */,
 788                        false            /* clear_all_soft_refs */,
 789                        size             /* size */,
 790                        is_tlab          /* is_tlab */,
 791                        number_of_generations() - 1 /* max_level */);
 792   }
 793 
 794   result = gch->attempt_allocation(size, is_tlab, false /*first_only*/);
 795 
 796   if (result != NULL) {
 797     assert(gch->is_in_reserved(result), "result not in heap");
 798     return result;
 799   }
 800 
 801   // OK, collection failed, try expansion.
 802   result = expand_heap_and_allocate(size, is_tlab);
 803   if (result != NULL) {
 804     return result;
 805   }
 806 
 807   // If we reach this point, we're really out of memory. Try every trick
 808   // we can to reclaim memory. Force collection of soft references. Force
 809   // a complete compaction of the heap. Any additional methods for finding
 810   // free memory should be here, especially if they are expensive. If this
 811   // attempt fails, an OOM exception will be thrown.
 812   {
 813     UIntFlagSetting flag_change(MarkSweepAlwaysCompactCount, 1); // Make sure the heap is fully compacted
 814 
 815     gch->do_collection(true             /* full */,
 816                        true             /* clear_all_soft_refs */,
 817                        size             /* size */,
 818                        is_tlab          /* is_tlab */,
 819                        number_of_generations() - 1 /* max_level */);
 820   }
 821 
 822   result = gch->attempt_allocation(size, is_tlab, false /* first_only */);
 823   if (result != NULL) {
 824     assert(gch->is_in_reserved(result), "result not in heap");
 825     return result;
 826   }
 827 
 828   assert(!should_clear_all_soft_refs(),
 829     "Flag should have been handled and cleared prior to this point");
 830 
 831   // What else?  We might try synchronous finalization later.  If the total
 832   // space available is large enough for the allocation, then a more
 833   // complete compaction phase than we've tried so far might be
 834   // appropriate.
 835   return NULL;
 836 }
 837 
 838 MetaWord* CollectorPolicy::satisfy_failed_metadata_allocation(
 839                                                  ClassLoaderData* loader_data,
 840                                                  size_t word_size,
 841                                                  Metaspace::MetadataType mdtype) {
 842   uint loop_count = 0;
 843   uint gc_count = 0;
 844   uint full_gc_count = 0;
 845 
 846   assert(!Heap_lock->owned_by_self(), "Should not be holding the Heap_lock");
 847 
 848   do {
 849     MetaWord* result = NULL;
 850     if (GC_locker::is_active_and_needs_gc()) {
 851       // If the GC_locker is active, just expand and allocate.
 852       // If that does not succeed, wait if this thread is not
 853       // in a critical section itself.
 854       result =
 855         loader_data->metaspace_non_null()->expand_and_allocate(word_size,
 856                                                                mdtype);
 857       if (result != NULL) {
 858         return result;
 859       }
 860       JavaThread* jthr = JavaThread::current();
 861       if (!jthr->in_critical()) {
 862         // Wait for JNI critical section to be exited
 863         GC_locker::stall_until_clear();
 864         // The GC invoked by the last thread leaving the critical
 865         // section will be a young collection and a full collection
 866         // is (currently) needed for unloading classes so continue
 867         // to the next iteration to get a full GC.
 868         continue;
 869       } else {
 870         if (CheckJNICalls) {
 871           fatal("Possible deadlock due to allocating while"
 872                 " in jni critical section");
 873         }
 874         return NULL;
 875       }
 876     }
 877 
 878     {  // Need lock to get self consistent gc_count's
 879       MutexLocker ml(Heap_lock);
 880       gc_count      = Universe::heap()->total_collections();
 881       full_gc_count = Universe::heap()->total_full_collections();
 882     }
 883 
 884     // Generate a VM operation
 885     VM_CollectForMetadataAllocation op(loader_data,
 886                                        word_size,
 887                                        mdtype,
 888                                        gc_count,
 889                                        full_gc_count,
 890                                        GCCause::_metadata_GC_threshold);
 891     VMThread::execute(&op);
 892 
 893     // If GC was locked out, try again. Check before checking success because the
 894     // prologue could have succeeded and the GC still have been locked out.
 895     if (op.gc_locked()) {
 896       continue;
 897     }
 898 
 899     if (op.prologue_succeeded()) {
 900       return op.result();
 901     }
 902     loop_count++;
 903     if ((QueuedAllocationWarningCount > 0) &&
 904         (loop_count % QueuedAllocationWarningCount == 0)) {
 905       warning("satisfy_failed_metadata_allocation() retries %d times \n\t"
 906               " size=" SIZE_FORMAT, loop_count, word_size);
 907     }
 908   } while (true);  // Until a GC is done
 909 }
 910 
 911 // Return true if any of the following is true:
 912 // . the allocation won't fit into the current young gen heap
 913 // . gc locker is occupied (jni critical section)
 914 // . heap memory is tight -- the most recent previous collection
 915 //   was a full collection because a partial collection (would
 916 //   have) failed and is likely to fail again
 917 bool GenCollectorPolicy::should_try_older_generation_allocation(
 918         size_t word_size) const {
 919   GenCollectedHeap* gch = GenCollectedHeap::heap();
 920   size_t gen0_capacity = gch->get_gen(0)->capacity_before_gc();
 921   return    (word_size > heap_word_size(gen0_capacity))
 922          || GC_locker::is_active_and_needs_gc()
 923          || gch->incremental_collection_failed();
 924 }
 925 
 926 
 927 //
 928 // MarkSweepPolicy methods
 929 //
 930 
 931 void MarkSweepPolicy::initialize_alignments() {
 932   _space_alignment = _gen_alignment = (uintx)Generation::GenGrain;
 933   _heap_alignment = compute_heap_alignment();
 934 }
 935 
 936 void MarkSweepPolicy::initialize_generations() {
 937   _generations = NEW_C_HEAP_ARRAY3(GenerationSpecPtr, number_of_generations(), mtGC, 0, AllocFailStrategy::RETURN_NULL);
 938   if (_generations == NULL) {
 939     vm_exit_during_initialization("Unable to allocate gen spec");
 940   }
 941 
 942   if (UseParNewGC) {
 943     _generations[0] = new GenerationSpec(Generation::ParNew, _initial_gen0_size, _max_gen0_size);
 944   } else {
 945     _generations[0] = new GenerationSpec(Generation::DefNew, _initial_gen0_size, _max_gen0_size);
 946   }
 947   _generations[1] = new GenerationSpec(Generation::MarkSweepCompact, _initial_gen1_size, _max_gen1_size);
 948 
 949   if (_generations[0] == NULL || _generations[1] == NULL) {
 950     vm_exit_during_initialization("Unable to allocate gen spec");
 951   }
 952 }
 953 
 954 void MarkSweepPolicy::initialize_gc_policy_counters() {
 955   // Initialize the policy counters - 2 collectors, 3 generations.
 956   if (UseParNewGC) {
 957     _gc_policy_counters = new GCPolicyCounters("ParNew:MSC", 2, 3);
 958   } else {
 959     _gc_policy_counters = new GCPolicyCounters("Copy:MSC", 2, 3);
 960   }
 961 }
 962 
 963 /////////////// Unit tests ///////////////
 964 
 965 #ifndef PRODUCT
 966 // Testing that the NewSize flag is handled correct is hard because it
 967 // depends on so many other configurable variables. This test only tries to
 968 // verify that there are some basic rules for NewSize honored by the policies.
 969 class TestGenCollectorPolicy {
 970 public:
 971   static void test_new_size() {
 972     size_t flag_value;
 973 
 974     save_flags();
 975 
 976     // If NewSize is set on the command line, it should be used
 977     // for both min and initial young size if less than min heap.
 978     flag_value = 20 * M;
 979     set_basic_flag_values();
 980     FLAG_SET_CMDLINE(uintx, NewSize, flag_value);
 981     verify_gen0_min(flag_value);
 982 
 983     set_basic_flag_values();
 984     FLAG_SET_CMDLINE(uintx, NewSize, flag_value);
 985     verify_gen0_initial(flag_value);
 986 
 987     // If NewSize is set on command line, but is larger than the min
 988     // heap size, it should only be used for initial young size.
 989     flag_value = 80 * M;
 990     set_basic_flag_values();
 991     FLAG_SET_CMDLINE(uintx, NewSize, flag_value);
 992     verify_gen0_initial(flag_value);
 993 
 994     // If NewSize has been ergonomically set, the collector policy
 995     // should use it for min but calculate the initial young size
 996     // using NewRatio.
 997     flag_value = 20 * M;
 998     set_basic_flag_values();
 999     FLAG_SET_ERGO(uintx, NewSize, flag_value);
1000     verify_gen0_min(flag_value);
1001 
1002     set_basic_flag_values();
1003     FLAG_SET_ERGO(uintx, NewSize, flag_value);
1004     verify_scaled_gen0_initial(InitialHeapSize);
1005 
1006     restore_flags();
1007   }
1008 
1009   static void test_old_size() {
1010       size_t flag_value;
1011 
1012       save_flags();
1013 
1014       // If OldSize is set on the command line, it should be used
1015       // for both min and initial old size if less than min heap.
1016       flag_value = 20 * M;
1017       set_basic_flag_values();
1018       FLAG_SET_CMDLINE(uintx, OldSize, flag_value);
1019       verify_gen1_min(flag_value);
1020 
1021       set_basic_flag_values();
1022       FLAG_SET_CMDLINE(uintx, OldSize, flag_value);
1023       verify_gen1_initial(flag_value);
1024 
1025       // If MaxNewSize is large, the maximum OldSize will be less than
1026       // what's requested on the command line and it should be reset
1027       // ergonomically.
1028       flag_value = 30 * M;
1029       set_basic_flag_values();
1030       FLAG_SET_CMDLINE(uintx, OldSize, flag_value);
1031       FLAG_SET_CMDLINE(uintx, MaxNewSize, 170*M);
1032       // Calculate what we expect the flag to be.
1033       flag_value = MaxHeapSize - MaxNewSize;
1034       verify_gen1_initial(flag_value);
1035 
1036   }
1037 
1038   static void verify_gen0_min(size_t expected) {
1039     MarkSweepPolicy msp;
1040     msp.initialize_all();
1041 
1042     assert(msp.min_gen0_size() <= expected, err_msg("%zu  > %zu", msp.min_gen0_size(), expected));
1043   }
1044 
1045   static void verify_gen0_initial(size_t expected) {
1046     MarkSweepPolicy msp;
1047     msp.initialize_all();
1048 
1049     assert(msp.initial_gen0_size() == expected, err_msg("%zu != %zu", msp.initial_gen0_size(), expected));
1050   }
1051 
1052   static void verify_scaled_gen0_initial(size_t initial_heap_size) {
1053     MarkSweepPolicy msp;
1054     msp.initialize_all();
1055 
1056     size_t expected = msp.scale_by_NewRatio_aligned(initial_heap_size);
1057     assert(msp.initial_gen0_size() == expected, err_msg("%zu != %zu", msp.initial_gen0_size(), expected));
1058     assert(FLAG_IS_ERGO(NewSize) && NewSize == expected,
1059         err_msg("NewSize should have been set ergonomically to %zu, but was %zu", expected, NewSize));
1060   }
1061 
1062   static void verify_gen1_min(size_t expected) {
1063     MarkSweepPolicy msp;
1064     msp.initialize_all();
1065 
1066     assert(msp.min_gen1_size() <= expected, err_msg("%zu  > %zu", msp.min_gen1_size(), expected));
1067   }
1068 
1069   static void verify_gen1_initial(size_t expected) {
1070     MarkSweepPolicy msp;
1071     msp.initialize_all();
1072 
1073     assert(msp.initial_gen1_size() == expected, err_msg("%zu != %zu", msp.initial_gen1_size(), expected));
1074   }
1075 
1076 
1077 private:
1078   static size_t original_InitialHeapSize;
1079   static size_t original_MaxHeapSize;
1080   static size_t original_MaxNewSize;
1081   static size_t original_MinHeapDeltaBytes;
1082   static size_t original_NewSize;
1083   static size_t original_OldSize;
1084 
1085   static void set_basic_flag_values() {
1086     FLAG_SET_ERGO(uintx, MaxHeapSize, 180 * M);
1087     FLAG_SET_ERGO(uintx, InitialHeapSize, 100 * M);
1088     FLAG_SET_ERGO(uintx, OldSize, 4 * M);
1089     FLAG_SET_ERGO(uintx, NewSize, 1 * M);
1090     FLAG_SET_ERGO(uintx, MaxNewSize, 80 * M);
1091     Arguments::set_min_heap_size(40 * M);
1092   }
1093 
1094   static void save_flags() {
1095     original_InitialHeapSize   = InitialHeapSize;
1096     original_MaxHeapSize       = MaxHeapSize;
1097     original_MaxNewSize        = MaxNewSize;
1098     original_MinHeapDeltaBytes = MinHeapDeltaBytes;
1099     original_NewSize           = NewSize;
1100     original_OldSize           = OldSize;
1101   }
1102 
1103   static void restore_flags() {
1104     InitialHeapSize   = original_InitialHeapSize;
1105     MaxHeapSize       = original_MaxHeapSize;
1106     MaxNewSize        = original_MaxNewSize;
1107     MinHeapDeltaBytes = original_MinHeapDeltaBytes;
1108     NewSize           = original_NewSize;
1109     OldSize           = original_OldSize;
1110   }
1111 };
1112 
1113 size_t TestGenCollectorPolicy::original_InitialHeapSize   = 0;
1114 size_t TestGenCollectorPolicy::original_MaxHeapSize       = 0;
1115 size_t TestGenCollectorPolicy::original_MaxNewSize        = 0;
1116 size_t TestGenCollectorPolicy::original_MinHeapDeltaBytes = 0;
1117 size_t TestGenCollectorPolicy::original_NewSize           = 0;
1118 size_t TestGenCollectorPolicy::original_OldSize           = 0;
1119 
1120 void TestNewSize_test() {
1121   TestGenCollectorPolicy::test_new_size();
1122 }
1123 
1124 void TestOldSize_test() {
1125   TestGenCollectorPolicy::test_old_size();
1126 }
1127 
1128 #endif