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   // There is only the GenRemSet in Hotspot and only the GenRemSet::CardTable
 182   // is supported.
 183   // Requirements of any new remembered set implementations must be added here.
 184   size_t alignment = GenRemSet::max_alignment_constraint(GenRemSet::CardTable);
 185 
 186   // Parallel GC does its own alignment of the generations to avoid requiring a
 187   // large page (256M on some platforms) for the permanent generation.  The
 188   // other collectors should also be updated to do their own alignment and then
 189   // this use of lcm() should be removed.
 190   if (UseLargePages && !UseParallelGC) {
 191       // in presence of large pages we have to make sure that our
 192       // alignment is large page aware
 193       alignment = lcm(os::large_page_size(), alignment);
 194   }
 195 
 196   return alignment;
 197 }
 198 
 199 // GenCollectorPolicy methods.
 200 
 201 size_t GenCollectorPolicy::scale_by_NewRatio_aligned(size_t base_size) {
 202   return align_size_down_bounded(base_size / (NewRatio + 1), _gen_alignment);
 203 }
 204 
 205 size_t GenCollectorPolicy::bound_minus_alignment(size_t desired_size,
 206                                                  size_t maximum_size) {
 207   size_t max_minus = maximum_size - _gen_alignment;
 208   return desired_size < max_minus ? desired_size : max_minus;
 209 }
 210 
 211 
 212 void GenCollectorPolicy::initialize_size_policy(size_t init_eden_size,
 213                                                 size_t init_promo_size,
 214                                                 size_t init_survivor_size) {
 215   const double max_gc_pause_sec = ((double) MaxGCPauseMillis) / 1000.0;
 216   _size_policy = new AdaptiveSizePolicy(init_eden_size,
 217                                         init_promo_size,
 218                                         init_survivor_size,
 219                                         max_gc_pause_sec,
 220                                         GCTimeRatio);
 221 }
 222 
 223 size_t GenCollectorPolicy::young_gen_size_lower_bound() {
 224   // The young generation must be aligned and have room for eden + two survivors
 225   return align_size_up(3 * _space_alignment, _gen_alignment);
 226 }
 227 
 228 #ifdef ASSERT
 229 void GenCollectorPolicy::assert_flags() {
 230   CollectorPolicy::assert_flags();
 231   assert(NewSize >= _min_gen0_size, "Ergonomics decided on a too small young gen size");
 232   assert(NewSize <= MaxNewSize, "Ergonomics decided on incompatible initial and maximum young gen sizes");
 233   assert(FLAG_IS_DEFAULT(MaxNewSize) || MaxNewSize < MaxHeapSize, "Ergonomics decided on incompatible maximum young gen and heap sizes");
 234   assert(NewSize % _gen_alignment == 0, "NewSize alignment");
 235   assert(FLAG_IS_DEFAULT(MaxNewSize) || MaxNewSize % _gen_alignment == 0, "MaxNewSize alignment");
 236 }
 237 
 238 void TwoGenerationCollectorPolicy::assert_flags() {
 239   GenCollectorPolicy::assert_flags();
 240   assert(OldSize + NewSize <= MaxHeapSize, "Ergonomics decided on incompatible generation and heap sizes");
 241   assert(OldSize % _gen_alignment == 0, "OldSize alignment");
 242 }
 243 
 244 void GenCollectorPolicy::assert_size_info() {
 245   CollectorPolicy::assert_size_info();
 246   // GenCollectorPolicy::initialize_size_info may update the MaxNewSize
 247   assert(MaxNewSize < MaxHeapSize, "Ergonomics decided on incompatible maximum young and heap sizes");
 248   assert(NewSize == _initial_gen0_size, "Discrepancy between NewSize flag and local storage");
 249   assert(MaxNewSize == _max_gen0_size, "Discrepancy between MaxNewSize flag and local storage");
 250   assert(_min_gen0_size <= _initial_gen0_size, "Ergonomics decided on incompatible minimum and initial young gen sizes");
 251   assert(_initial_gen0_size <= _max_gen0_size, "Ergonomics decided on incompatible initial and maximum young gen sizes");
 252   assert(_min_gen0_size % _gen_alignment == 0, "_min_gen0_size alignment");
 253   assert(_initial_gen0_size % _gen_alignment == 0, "_initial_gen0_size alignment");
 254   assert(_max_gen0_size % _gen_alignment == 0, "_max_gen0_size alignment");
 255 }
 256 
 257 void TwoGenerationCollectorPolicy::assert_size_info() {
 258   GenCollectorPolicy::assert_size_info();
 259   assert(OldSize == _initial_gen1_size, "Discrepancy between OldSize flag and local storage");
 260   assert(_min_gen1_size <= _initial_gen1_size, "Ergonomics decided on incompatible minimum and initial old gen sizes");
 261   assert(_initial_gen1_size <= _max_gen1_size, "Ergonomics decided on incompatible initial and maximum old gen sizes");
 262   assert(_max_gen1_size % _gen_alignment == 0, "_max_gen1_size alignment");
 263   assert(_initial_gen1_size % _gen_alignment == 0, "_initial_gen1_size alignment");
 264   assert(_max_heap_byte_size <= (_max_gen0_size + _max_gen1_size), "Total maximum heap sizes must be sum of generation maximum sizes");
 265 }
 266 #endif // ASSERT
 267 
 268 void GenCollectorPolicy::initialize_flags() {
 269   CollectorPolicy::initialize_flags();
 270 
 271   assert(_gen_alignment != 0, "Generation alignment not set up properly");
 272   assert(_heap_alignment >= _gen_alignment,
 273          err_msg("heap_alignment: " SIZE_FORMAT " less than gen_alignment: " SIZE_FORMAT,
 274                  _heap_alignment, _gen_alignment));
 275   assert(_gen_alignment % _space_alignment == 0,
 276          err_msg("gen_alignment: " SIZE_FORMAT " not aligned by space_alignment: " SIZE_FORMAT,
 277                  _gen_alignment, _space_alignment));
 278   assert(_heap_alignment % _gen_alignment == 0,
 279          err_msg("heap_alignment: " SIZE_FORMAT " not aligned by gen_alignment: " SIZE_FORMAT,
 280                  _heap_alignment, _gen_alignment));
 281 
 282   // All generational heaps have a youngest gen; handle those flags here
 283 
 284   // Make sure the heap is large enough for two generations
 285   uintx smallest_new_size = young_gen_size_lower_bound();
 286   uintx smallest_heap_size = align_size_up(smallest_new_size + align_size_up(_space_alignment, _gen_alignment),
 287                                            _heap_alignment);
 288   if (MaxHeapSize < smallest_heap_size) {
 289     FLAG_SET_ERGO(uintx, MaxHeapSize, smallest_heap_size);
 290     _max_heap_byte_size = MaxHeapSize;
 291   }
 292   // If needed, synchronize _min_heap_byte size and _initial_heap_byte_size
 293   if (_min_heap_byte_size < smallest_heap_size) {
 294     _min_heap_byte_size = smallest_heap_size;
 295     if (InitialHeapSize < _min_heap_byte_size) {
 296       FLAG_SET_ERGO(uintx, InitialHeapSize, smallest_heap_size);
 297       _initial_heap_byte_size = smallest_heap_size;
 298     }
 299   }
 300 
 301   // Now take the actual NewSize into account. We will silently increase NewSize
 302   // if the user specified a smaller value.
 303   smallest_new_size = MAX2(smallest_new_size, (uintx)align_size_down(NewSize, _gen_alignment));
 304   if (smallest_new_size != NewSize) {
 305     FLAG_SET_ERGO(uintx, NewSize, smallest_new_size);
 306   }
 307   _initial_gen0_size = NewSize;
 308 
 309   if (!FLAG_IS_DEFAULT(MaxNewSize)) {
 310     uintx min_new_size = MAX2(_gen_alignment, _min_gen0_size);
 311 
 312     if (MaxNewSize >= MaxHeapSize) {
 313       // Make sure there is room for an old generation
 314       uintx smaller_max_new_size = MaxHeapSize - _gen_alignment;
 315       if (FLAG_IS_CMDLINE(MaxNewSize)) {
 316         warning("MaxNewSize (" SIZE_FORMAT "k) is equal to or greater than the entire "
 317                 "heap (" SIZE_FORMAT "k).  A new max generation size of " SIZE_FORMAT "k will be used.",
 318                 MaxNewSize/K, MaxHeapSize/K, smaller_max_new_size/K);
 319       }
 320       FLAG_SET_ERGO(uintx, MaxNewSize, smaller_max_new_size);
 321       if (NewSize > MaxNewSize) {
 322         FLAG_SET_ERGO(uintx, NewSize, MaxNewSize);
 323         _initial_gen0_size = NewSize;
 324       }
 325     } else if (MaxNewSize < min_new_size) {
 326       FLAG_SET_ERGO(uintx, MaxNewSize, min_new_size);
 327     } else if (!is_size_aligned(MaxNewSize, _gen_alignment)) {
 328       FLAG_SET_ERGO(uintx, MaxNewSize, align_size_down(MaxNewSize, _gen_alignment));
 329     }
 330     _max_gen0_size = MaxNewSize;
 331   }
 332 
 333   if (NewSize > MaxNewSize) {
 334     // At this point this should only happen if the user specifies a large NewSize and/or
 335     // a small (but not too small) MaxNewSize.
 336     if (FLAG_IS_CMDLINE(MaxNewSize)) {
 337       warning("NewSize (" SIZE_FORMAT "k) is greater than the MaxNewSize (" SIZE_FORMAT "k). "
 338               "A new max generation size of " SIZE_FORMAT "k will be used.",
 339               NewSize/K, MaxNewSize/K, NewSize/K);
 340     }
 341     FLAG_SET_ERGO(uintx, MaxNewSize, NewSize);
 342     _max_gen0_size = MaxNewSize;
 343   }
 344 
 345   if (SurvivorRatio < 1 || NewRatio < 1) {
 346     vm_exit_during_initialization("Invalid young gen ratio specified");
 347   }
 348 
 349   DEBUG_ONLY(GenCollectorPolicy::assert_flags();)
 350 }
 351 
 352 void TwoGenerationCollectorPolicy::initialize_flags() {
 353   GenCollectorPolicy::initialize_flags();
 354 
 355   if (!is_size_aligned(OldSize, _gen_alignment)) {
 356     FLAG_SET_ERGO(uintx, OldSize, align_size_down(OldSize, _gen_alignment));
 357   }
 358 
 359   if (FLAG_IS_CMDLINE(OldSize) && FLAG_IS_DEFAULT(MaxHeapSize)) {
 360     // NewRatio will be used later to set the young generation size so we use
 361     // it to calculate how big the heap should be based on the requested OldSize
 362     // and NewRatio.
 363     assert(NewRatio > 0, "NewRatio should have been set up earlier");
 364     size_t calculated_heapsize = (OldSize / NewRatio) * (NewRatio + 1);
 365 
 366     calculated_heapsize = align_size_up(calculated_heapsize, _heap_alignment);
 367     FLAG_SET_ERGO(uintx, MaxHeapSize, calculated_heapsize);
 368     _max_heap_byte_size = MaxHeapSize;
 369     FLAG_SET_ERGO(uintx, InitialHeapSize, calculated_heapsize);
 370     _initial_heap_byte_size = InitialHeapSize;
 371   }
 372 
 373   // adjust max heap size if necessary
 374   if (NewSize + OldSize > MaxHeapSize) {
 375     if (_max_heap_size_cmdline) {
 376       // somebody set a maximum heap size with the intention that we should not
 377       // exceed it. Adjust New/OldSize as necessary.
 378       uintx calculated_size = NewSize + OldSize;
 379       double shrink_factor = (double) MaxHeapSize / calculated_size;
 380       uintx smaller_new_size = align_size_down((uintx)(NewSize * shrink_factor), _gen_alignment);
 381       FLAG_SET_ERGO(uintx, NewSize, MAX2(young_gen_size_lower_bound(), smaller_new_size));
 382       _initial_gen0_size = NewSize;
 383 
 384       // OldSize is already aligned because above we aligned MaxHeapSize to
 385       // _heap_alignment, and we just made sure that NewSize is aligned to
 386       // _gen_alignment. In initialize_flags() we verified that _heap_alignment
 387       // is a multiple of _gen_alignment.
 388       FLAG_SET_ERGO(uintx, OldSize, MaxHeapSize - NewSize);
 389     } else {
 390       FLAG_SET_ERGO(uintx, MaxHeapSize, align_size_up(NewSize + OldSize, _heap_alignment));
 391       _max_heap_byte_size = MaxHeapSize;
 392     }
 393   }
 394 
 395   always_do_update_barrier = UseConcMarkSweepGC;
 396 
 397   DEBUG_ONLY(TwoGenerationCollectorPolicy::assert_flags();)
 398 }
 399 
 400 // Values set on the command line win over any ergonomically
 401 // set command line parameters.
 402 // Ergonomic choice of parameters are done before this
 403 // method is called.  Values for command line parameters such as NewSize
 404 // and MaxNewSize feed those ergonomic choices into this method.
 405 // This method makes the final generation sizings consistent with
 406 // themselves and with overall heap sizings.
 407 // In the absence of explicitly set command line flags, policies
 408 // such as the use of NewRatio are used to size the generation.
 409 void GenCollectorPolicy::initialize_size_info() {
 410   CollectorPolicy::initialize_size_info();
 411 
 412   // _space_alignment is used for alignment within a generation.
 413   // There is additional alignment done down stream for some
 414   // collectors that sometimes causes unwanted rounding up of
 415   // generations sizes.
 416 
 417   // Determine maximum size of gen0
 418 
 419   size_t max_new_size = 0;
 420   if (!FLAG_IS_DEFAULT(MaxNewSize)) {
 421     max_new_size = MaxNewSize;
 422   } else {
 423     max_new_size = scale_by_NewRatio_aligned(_max_heap_byte_size);
 424     // Bound the maximum size by NewSize below (since it historically
 425     // would have been NewSize and because the NewRatio calculation could
 426     // yield a size that is too small) and bound it by MaxNewSize above.
 427     // Ergonomics plays here by previously calculating the desired
 428     // NewSize and MaxNewSize.
 429     max_new_size = MIN2(MAX2(max_new_size, NewSize), MaxNewSize);
 430   }
 431   assert(max_new_size > 0, "All paths should set max_new_size");
 432 
 433   // Given the maximum gen0 size, determine the initial and
 434   // minimum gen0 sizes.
 435 
 436   if (_max_heap_byte_size == _min_heap_byte_size) {
 437     // The maximum and minimum heap sizes are the same so
 438     // the generations minimum and initial must be the
 439     // same as its maximum.
 440     _min_gen0_size = max_new_size;
 441     _initial_gen0_size = max_new_size;
 442     _max_gen0_size = max_new_size;
 443   } else {
 444     size_t desired_new_size = 0;
 445     if (!FLAG_IS_DEFAULT(NewSize)) {
 446       // If NewSize is set ergonomically (for example by cms), it
 447       // would make sense to use it.  If it is used, also use it
 448       // to set the initial size.  Although there is no reason
 449       // the minimum size and the initial size have to be the same,
 450       // the current implementation gets into trouble during the calculation
 451       // of the tenured generation sizes if they are different.
 452       // Note that this makes the initial size and the minimum size
 453       // generally small compared to the NewRatio calculation.
 454       _min_gen0_size = NewSize;
 455       desired_new_size = NewSize;
 456       max_new_size = MAX2(max_new_size, NewSize);
 457     } else {
 458       // For the case where NewSize is the default, use NewRatio
 459       // to size the minimum and initial generation sizes.
 460       // Use the default NewSize as the floor for these values.  If
 461       // NewRatio is overly large, the resulting sizes can be too
 462       // small.
 463       _min_gen0_size = MAX2(scale_by_NewRatio_aligned(_min_heap_byte_size), NewSize);
 464       desired_new_size =
 465         MAX2(scale_by_NewRatio_aligned(_initial_heap_byte_size), NewSize);
 466     }
 467 
 468     assert(_min_gen0_size > 0, "Sanity check");
 469     _initial_gen0_size = desired_new_size;
 470     _max_gen0_size = max_new_size;
 471 
 472     // At this point the desirable initial and minimum sizes have been
 473     // determined without regard to the maximum sizes.
 474 
 475     // Bound the sizes by the corresponding overall heap sizes.
 476     _min_gen0_size = bound_minus_alignment(_min_gen0_size, _min_heap_byte_size);
 477     _initial_gen0_size = bound_minus_alignment(_initial_gen0_size, _initial_heap_byte_size);
 478     _max_gen0_size = bound_minus_alignment(_max_gen0_size, _max_heap_byte_size);
 479 
 480     // At this point all three sizes have been checked against the
 481     // maximum sizes but have not been checked for consistency
 482     // among the three.
 483 
 484     // Final check min <= initial <= max
 485     _min_gen0_size = MIN2(_min_gen0_size, _max_gen0_size);
 486     _initial_gen0_size = MAX2(MIN2(_initial_gen0_size, _max_gen0_size), _min_gen0_size);
 487     _min_gen0_size = MIN2(_min_gen0_size, _initial_gen0_size);
 488   }
 489 
 490   // Write back to flags if necessary
 491   if (NewSize != _initial_gen0_size) {
 492     FLAG_SET_ERGO(uintx, NewSize, _initial_gen0_size);
 493   }
 494 
 495   if (MaxNewSize != _max_gen0_size) {
 496     FLAG_SET_ERGO(uintx, MaxNewSize, _max_gen0_size);
 497   }
 498 
 499   if (PrintGCDetails && Verbose) {
 500     gclog_or_tty->print_cr("1: Minimum gen0 " SIZE_FORMAT "  Initial gen0 "
 501       SIZE_FORMAT "  Maximum gen0 " SIZE_FORMAT,
 502       _min_gen0_size, _initial_gen0_size, _max_gen0_size);
 503   }
 504 
 505   DEBUG_ONLY(GenCollectorPolicy::assert_size_info();)
 506 }
 507 
 508 // Call this method during the sizing of the gen1 to make
 509 // adjustments to gen0 because of gen1 sizing policy.  gen0 initially has
 510 // the most freedom in sizing because it is done before the
 511 // policy for gen1 is applied.  Once gen1 policies have been applied,
 512 // there may be conflicts in the shape of the heap and this method
 513 // is used to make the needed adjustments.  The application of the
 514 // policies could be more sophisticated (iterative for example) but
 515 // keeping it simple also seems a worthwhile goal.
 516 bool TwoGenerationCollectorPolicy::adjust_gen0_sizes(size_t* gen0_size_ptr,
 517                                                      size_t* gen1_size_ptr,
 518                                                      const size_t heap_size,
 519                                                      const size_t min_gen1_size) {
 520   bool result = false;
 521 
 522   if ((*gen1_size_ptr + *gen0_size_ptr) > heap_size) {
 523     uintx smallest_new_size = young_gen_size_lower_bound();
 524     if ((heap_size < (*gen0_size_ptr + min_gen1_size)) &&
 525         (heap_size >= min_gen1_size + smallest_new_size)) {
 526       // Adjust gen0 down to accommodate min_gen1_size
 527       *gen0_size_ptr = align_size_down_bounded(heap_size - min_gen1_size, _gen_alignment);
 528       assert(*gen0_size_ptr > 0, "Min gen0 is too large");
 529       result = true;
 530     } else {
 531       *gen1_size_ptr = align_size_down_bounded(heap_size - *gen0_size_ptr, _gen_alignment);
 532     }
 533   }
 534   return result;
 535 }
 536 
 537 // Minimum sizes of the generations may be different than
 538 // the initial sizes.  An inconsistently is permitted here
 539 // in the total size that can be specified explicitly by
 540 // command line specification of OldSize and NewSize and
 541 // also a command line specification of -Xms.  Issue a warning
 542 // but allow the values to pass.
 543 
 544 void TwoGenerationCollectorPolicy::initialize_size_info() {
 545   GenCollectorPolicy::initialize_size_info();
 546 
 547   // At this point the minimum, initial and maximum sizes
 548   // of the overall heap and of gen0 have been determined.
 549   // The maximum gen1 size can be determined from the maximum gen0
 550   // and maximum heap size since no explicit flags exits
 551   // for setting the gen1 maximum.
 552   _max_gen1_size = MAX2(_max_heap_byte_size - _max_gen0_size, _gen_alignment);
 553 
 554   // If no explicit command line flag has been set for the
 555   // gen1 size, use what is left for gen1.
 556   if (!FLAG_IS_CMDLINE(OldSize)) {
 557     // The user has not specified any value but the ergonomics
 558     // may have chosen a value (which may or may not be consistent
 559     // with the overall heap size).  In either case make
 560     // the minimum, maximum and initial sizes consistent
 561     // with the gen0 sizes and the overall heap sizes.
 562     _min_gen1_size = MAX2(_min_heap_byte_size - _min_gen0_size, _gen_alignment);
 563     _initial_gen1_size = MAX2(_initial_heap_byte_size - _initial_gen0_size, _gen_alignment);
 564     // _max_gen1_size has already been made consistent above
 565     FLAG_SET_ERGO(uintx, OldSize, _initial_gen1_size);
 566   } else {
 567     // It's been explicitly set on the command line.  Use the
 568     // OldSize and then determine the consequences.
 569     _min_gen1_size = MIN2(OldSize, _min_heap_byte_size - _min_gen0_size);
 570     _initial_gen1_size = OldSize;
 571 
 572     // If the user has explicitly set an OldSize that is inconsistent
 573     // with other command line flags, issue a warning.
 574     // The generation minimums and the overall heap mimimum should
 575     // be within one generation alignment.
 576     if ((_min_gen1_size + _min_gen0_size + _gen_alignment) < _min_heap_byte_size) {
 577       warning("Inconsistency between minimum heap size and minimum "
 578               "generation sizes: using minimum heap = " SIZE_FORMAT,
 579               _min_heap_byte_size);
 580     }
 581     if (OldSize > _max_gen1_size) {
 582       warning("Inconsistency between maximum heap size and maximum "
 583               "generation sizes: using maximum heap = " SIZE_FORMAT
 584               " -XX:OldSize flag is being ignored",
 585               _max_heap_byte_size);
 586     }
 587     // If there is an inconsistency between the OldSize and the minimum and/or
 588     // initial size of gen0, since OldSize was explicitly set, OldSize wins.
 589     if (adjust_gen0_sizes(&_min_gen0_size, &_min_gen1_size,
 590                           _min_heap_byte_size, _min_gen1_size)) {
 591       if (PrintGCDetails && Verbose) {
 592         gclog_or_tty->print_cr("2: Minimum gen0 " SIZE_FORMAT "  Initial gen0 "
 593               SIZE_FORMAT "  Maximum gen0 " SIZE_FORMAT,
 594               _min_gen0_size, _initial_gen0_size, _max_gen0_size);
 595       }
 596     }
 597     // Initial size
 598     if (adjust_gen0_sizes(&_initial_gen0_size, &_initial_gen1_size,
 599                           _initial_heap_byte_size, _initial_gen1_size)) {
 600       if (PrintGCDetails && Verbose) {
 601         gclog_or_tty->print_cr("3: Minimum gen0 " SIZE_FORMAT "  Initial gen0 "
 602           SIZE_FORMAT "  Maximum gen0 " SIZE_FORMAT,
 603           _min_gen0_size, _initial_gen0_size, _max_gen0_size);
 604       }
 605     }
 606   }
 607   // Enforce the maximum gen1 size.
 608   _min_gen1_size = MIN2(_min_gen1_size, _max_gen1_size);
 609 
 610   // Check that min gen1 <= initial gen1 <= max gen1
 611   _initial_gen1_size = MAX2(_initial_gen1_size, _min_gen1_size);
 612   _initial_gen1_size = MIN2(_initial_gen1_size, _max_gen1_size);
 613 
 614   // Write back to flags if necessary
 615   if (NewSize != _initial_gen0_size) {
 616     FLAG_SET_ERGO(uintx, NewSize, _max_gen0_size);
 617   }
 618 
 619   if (MaxNewSize != _max_gen0_size) {
 620     FLAG_SET_ERGO(uintx, MaxNewSize, _max_gen0_size);
 621   }
 622 
 623   if (OldSize != _initial_gen1_size) {
 624     FLAG_SET_ERGO(uintx, OldSize, _initial_gen1_size);
 625   }
 626 
 627   if (PrintGCDetails && Verbose) {
 628     gclog_or_tty->print_cr("Minimum gen1 " SIZE_FORMAT "  Initial gen1 "
 629       SIZE_FORMAT "  Maximum gen1 " SIZE_FORMAT,
 630       _min_gen1_size, _initial_gen1_size, _max_gen1_size);
 631   }
 632 
 633   DEBUG_ONLY(TwoGenerationCollectorPolicy::assert_size_info();)
 634 }
 635 
 636 HeapWord* GenCollectorPolicy::mem_allocate_work(size_t size,
 637                                         bool is_tlab,
 638                                         bool* gc_overhead_limit_was_exceeded) {
 639   GenCollectedHeap *gch = GenCollectedHeap::heap();
 640 
 641   debug_only(gch->check_for_valid_allocation_state());
 642   assert(gch->no_gc_in_progress(), "Allocation during gc not allowed");
 643 
 644   // In general gc_overhead_limit_was_exceeded should be false so
 645   // set it so here and reset it to true only if the gc time
 646   // limit is being exceeded as checked below.
 647   *gc_overhead_limit_was_exceeded = false;
 648 
 649   HeapWord* result = NULL;
 650 
 651   // Loop until the allocation is satisified,
 652   // or unsatisfied after GC.
 653   for (int try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) {
 654     HandleMark hm; // discard any handles allocated in each iteration
 655 
 656     // First allocation attempt is lock-free.
 657     Generation *gen0 = gch->get_gen(0);
 658     assert(gen0->supports_inline_contig_alloc(),
 659       "Otherwise, must do alloc within heap lock");
 660     if (gen0->should_allocate(size, is_tlab)) {
 661       result = gen0->par_allocate(size, is_tlab);
 662       if (result != NULL) {
 663         assert(gch->is_in_reserved(result), "result not in heap");
 664         return result;
 665       }
 666     }
 667     unsigned int gc_count_before;  // read inside the Heap_lock locked region
 668     {
 669       MutexLocker ml(Heap_lock);
 670       if (PrintGC && Verbose) {
 671         gclog_or_tty->print_cr("TwoGenerationCollectorPolicy::mem_allocate_work:"
 672                       " attempting locked slow path allocation");
 673       }
 674       // Note that only large objects get a shot at being
 675       // allocated in later generations.
 676       bool first_only = ! should_try_older_generation_allocation(size);
 677 
 678       result = gch->attempt_allocation(size, is_tlab, first_only);
 679       if (result != NULL) {
 680         assert(gch->is_in_reserved(result), "result not in heap");
 681         return result;
 682       }
 683 
 684       if (GC_locker::is_active_and_needs_gc()) {
 685         if (is_tlab) {
 686           return NULL;  // Caller will retry allocating individual object
 687         }
 688         if (!gch->is_maximal_no_gc()) {
 689           // Try and expand heap to satisfy request
 690           result = expand_heap_and_allocate(size, is_tlab);
 691           // result could be null if we are out of space
 692           if (result != NULL) {
 693             return result;
 694           }
 695         }
 696 
 697         if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
 698           return NULL; // we didn't get to do a GC and we didn't get any memory
 699         }
 700 
 701         // If this thread is not in a jni critical section, we stall
 702         // the requestor until the critical section has cleared and
 703         // GC allowed. When the critical section clears, a GC is
 704         // initiated by the last thread exiting the critical section; so
 705         // we retry the allocation sequence from the beginning of the loop,
 706         // rather than causing more, now probably unnecessary, GC attempts.
 707         JavaThread* jthr = JavaThread::current();
 708         if (!jthr->in_critical()) {
 709           MutexUnlocker mul(Heap_lock);
 710           // Wait for JNI critical section to be exited
 711           GC_locker::stall_until_clear();
 712           gclocker_stalled_count += 1;
 713           continue;
 714         } else {
 715           if (CheckJNICalls) {
 716             fatal("Possible deadlock due to allocating while"
 717                   " in jni critical section");
 718           }
 719           return NULL;
 720         }
 721       }
 722 
 723       // Read the gc count while the heap lock is held.
 724       gc_count_before = Universe::heap()->total_collections();
 725     }
 726 
 727     VM_GenCollectForAllocation op(size, is_tlab, gc_count_before);
 728     VMThread::execute(&op);
 729     if (op.prologue_succeeded()) {
 730       result = op.result();
 731       if (op.gc_locked()) {
 732          assert(result == NULL, "must be NULL if gc_locked() is true");
 733          continue;  // retry and/or stall as necessary
 734       }
 735 
 736       // Allocation has failed and a collection
 737       // has been done.  If the gc time limit was exceeded the
 738       // this time, return NULL so that an out-of-memory
 739       // will be thrown.  Clear gc_overhead_limit_exceeded
 740       // so that the overhead exceeded does not persist.
 741 
 742       const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
 743       const bool softrefs_clear = all_soft_refs_clear();
 744 
 745       if (limit_exceeded && softrefs_clear) {
 746         *gc_overhead_limit_was_exceeded = true;
 747         size_policy()->set_gc_overhead_limit_exceeded(false);
 748         if (op.result() != NULL) {
 749           CollectedHeap::fill_with_object(op.result(), size);
 750         }
 751         return NULL;
 752       }
 753       assert(result == NULL || gch->is_in_reserved(result),
 754              "result not in heap");
 755       return result;
 756     }
 757 
 758     // Give a warning if we seem to be looping forever.
 759     if ((QueuedAllocationWarningCount > 0) &&
 760         (try_count % QueuedAllocationWarningCount == 0)) {
 761           warning("TwoGenerationCollectorPolicy::mem_allocate_work retries %d times \n\t"
 762                   " size=%d %s", try_count, size, is_tlab ? "(TLAB)" : "");
 763     }
 764   }
 765 }
 766 
 767 HeapWord* GenCollectorPolicy::expand_heap_and_allocate(size_t size,
 768                                                        bool   is_tlab) {
 769   GenCollectedHeap *gch = GenCollectedHeap::heap();
 770   HeapWord* result = NULL;
 771   for (int i = number_of_generations() - 1; i >= 0 && result == NULL; i--) {
 772     Generation *gen = gch->get_gen(i);
 773     if (gen->should_allocate(size, is_tlab)) {
 774       result = gen->expand_and_allocate(size, is_tlab);
 775     }
 776   }
 777   assert(result == NULL || gch->is_in_reserved(result), "result not in heap");
 778   return result;
 779 }
 780 
 781 HeapWord* GenCollectorPolicy::satisfy_failed_allocation(size_t size,
 782                                                         bool   is_tlab) {
 783   GenCollectedHeap *gch = GenCollectedHeap::heap();
 784   GCCauseSetter x(gch, GCCause::_allocation_failure);
 785   HeapWord* result = NULL;
 786 
 787   assert(size != 0, "Precondition violated");
 788   if (GC_locker::is_active_and_needs_gc()) {
 789     // GC locker is active; instead of a collection we will attempt
 790     // to expand the heap, if there's room for expansion.
 791     if (!gch->is_maximal_no_gc()) {
 792       result = expand_heap_and_allocate(size, is_tlab);
 793     }
 794     return result;   // could be null if we are out of space
 795   } else if (!gch->incremental_collection_will_fail(false /* don't consult_young */)) {
 796     // Do an incremental collection.
 797     gch->do_collection(false            /* full */,
 798                        false            /* clear_all_soft_refs */,
 799                        size             /* size */,
 800                        is_tlab          /* is_tlab */,
 801                        number_of_generations() - 1 /* max_level */);
 802   } else {
 803     if (Verbose && PrintGCDetails) {
 804       gclog_or_tty->print(" :: Trying full because partial may fail :: ");
 805     }
 806     // Try a full collection; see delta for bug id 6266275
 807     // for the original code and why this has been simplified
 808     // with from-space allocation criteria modified and
 809     // such allocation moved out of the safepoint path.
 810     gch->do_collection(true             /* full */,
 811                        false            /* clear_all_soft_refs */,
 812                        size             /* size */,
 813                        is_tlab          /* is_tlab */,
 814                        number_of_generations() - 1 /* max_level */);
 815   }
 816 
 817   result = gch->attempt_allocation(size, is_tlab, false /*first_only*/);
 818 
 819   if (result != NULL) {
 820     assert(gch->is_in_reserved(result), "result not in heap");
 821     return result;
 822   }
 823 
 824   // OK, collection failed, try expansion.
 825   result = expand_heap_and_allocate(size, is_tlab);
 826   if (result != NULL) {
 827     return result;
 828   }
 829 
 830   // If we reach this point, we're really out of memory. Try every trick
 831   // we can to reclaim memory. Force collection of soft references. Force
 832   // a complete compaction of the heap. Any additional methods for finding
 833   // free memory should be here, especially if they are expensive. If this
 834   // attempt fails, an OOM exception will be thrown.
 835   {
 836     UIntFlagSetting flag_change(MarkSweepAlwaysCompactCount, 1); // Make sure the heap is fully compacted
 837 
 838     gch->do_collection(true             /* full */,
 839                        true             /* clear_all_soft_refs */,
 840                        size             /* size */,
 841                        is_tlab          /* is_tlab */,
 842                        number_of_generations() - 1 /* max_level */);
 843   }
 844 
 845   result = gch->attempt_allocation(size, is_tlab, false /* first_only */);
 846   if (result != NULL) {
 847     assert(gch->is_in_reserved(result), "result not in heap");
 848     return result;
 849   }
 850 
 851   assert(!should_clear_all_soft_refs(),
 852     "Flag should have been handled and cleared prior to this point");
 853 
 854   // What else?  We might try synchronous finalization later.  If the total
 855   // space available is large enough for the allocation, then a more
 856   // complete compaction phase than we've tried so far might be
 857   // appropriate.
 858   return NULL;
 859 }
 860 
 861 MetaWord* CollectorPolicy::satisfy_failed_metadata_allocation(
 862                                                  ClassLoaderData* loader_data,
 863                                                  size_t word_size,
 864                                                  Metaspace::MetadataType mdtype) {
 865   uint loop_count = 0;
 866   uint gc_count = 0;
 867   uint full_gc_count = 0;
 868 
 869   assert(!Heap_lock->owned_by_self(), "Should not be holding the Heap_lock");
 870 
 871   do {
 872     MetaWord* result = NULL;
 873     if (GC_locker::is_active_and_needs_gc()) {
 874       // If the GC_locker is active, just expand and allocate.
 875       // If that does not succeed, wait if this thread is not
 876       // in a critical section itself.
 877       result =
 878         loader_data->metaspace_non_null()->expand_and_allocate(word_size,
 879                                                                mdtype);
 880       if (result != NULL) {
 881         return result;
 882       }
 883       JavaThread* jthr = JavaThread::current();
 884       if (!jthr->in_critical()) {
 885         // Wait for JNI critical section to be exited
 886         GC_locker::stall_until_clear();
 887         // The GC invoked by the last thread leaving the critical
 888         // section will be a young collection and a full collection
 889         // is (currently) needed for unloading classes so continue
 890         // to the next iteration to get a full GC.
 891         continue;
 892       } else {
 893         if (CheckJNICalls) {
 894           fatal("Possible deadlock due to allocating while"
 895                 " in jni critical section");
 896         }
 897         return NULL;
 898       }
 899     }
 900 
 901     {  // Need lock to get self consistent gc_count's
 902       MutexLocker ml(Heap_lock);
 903       gc_count      = Universe::heap()->total_collections();
 904       full_gc_count = Universe::heap()->total_full_collections();
 905     }
 906 
 907     // Generate a VM operation
 908     VM_CollectForMetadataAllocation op(loader_data,
 909                                        word_size,
 910                                        mdtype,
 911                                        gc_count,
 912                                        full_gc_count,
 913                                        GCCause::_metadata_GC_threshold);
 914     VMThread::execute(&op);
 915 
 916     // If GC was locked out, try again.  Check
 917     // before checking success because the prologue
 918     // could have succeeded and the GC still have
 919     // been locked out.
 920     if (op.gc_locked()) {
 921       continue;
 922     }
 923 
 924     if (op.prologue_succeeded()) {
 925       return op.result();
 926     }
 927     loop_count++;
 928     if ((QueuedAllocationWarningCount > 0) &&
 929         (loop_count % QueuedAllocationWarningCount == 0)) {
 930       warning("satisfy_failed_metadata_allocation() retries %d times \n\t"
 931               " size=%d", loop_count, word_size);
 932     }
 933   } while (true);  // Until a GC is done
 934 }
 935 
 936 // Return true if any of the following is true:
 937 // . the allocation won't fit into the current young gen heap
 938 // . gc locker is occupied (jni critical section)
 939 // . heap memory is tight -- the most recent previous collection
 940 //   was a full collection because a partial collection (would
 941 //   have) failed and is likely to fail again
 942 bool GenCollectorPolicy::should_try_older_generation_allocation(
 943         size_t word_size) const {
 944   GenCollectedHeap* gch = GenCollectedHeap::heap();
 945   size_t gen0_capacity = gch->get_gen(0)->capacity_before_gc();
 946   return    (word_size > heap_word_size(gen0_capacity))
 947          || GC_locker::is_active_and_needs_gc()
 948          || gch->incremental_collection_failed();
 949 }
 950 
 951 
 952 //
 953 // MarkSweepPolicy methods
 954 //
 955 
 956 void MarkSweepPolicy::initialize_alignments() {
 957   _space_alignment = _gen_alignment = (uintx)Generation::GenGrain;
 958   _heap_alignment = compute_heap_alignment();
 959 }
 960 
 961 void MarkSweepPolicy::initialize_generations() {
 962   _generations = NEW_C_HEAP_ARRAY3(GenerationSpecPtr, number_of_generations(), mtGC, 0, AllocFailStrategy::RETURN_NULL);
 963   if (_generations == NULL) {
 964     vm_exit_during_initialization("Unable to allocate gen spec");
 965   }
 966 
 967   if (UseParNewGC) {
 968     _generations[0] = new GenerationSpec(Generation::ParNew, _initial_gen0_size, _max_gen0_size);
 969   } else {
 970     _generations[0] = new GenerationSpec(Generation::DefNew, _initial_gen0_size, _max_gen0_size);
 971   }
 972   _generations[1] = new GenerationSpec(Generation::MarkSweepCompact, _initial_gen1_size, _max_gen1_size);
 973 
 974   if (_generations[0] == NULL || _generations[1] == NULL) {
 975     vm_exit_during_initialization("Unable to allocate gen spec");
 976   }
 977 }
 978 
 979 void MarkSweepPolicy::initialize_gc_policy_counters() {
 980   // initialize the policy counters - 2 collectors, 3 generations
 981   if (UseParNewGC) {
 982     _gc_policy_counters = new GCPolicyCounters("ParNew:MSC", 2, 3);
 983   } else {
 984     _gc_policy_counters = new GCPolicyCounters("Copy:MSC", 2, 3);
 985   }
 986 }