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