1 /*
   2  * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "gc/shared/adaptiveSizePolicy.hpp"
  27 #include "gc/shared/cardTableRS.hpp"
  28 #include "gc/shared/collectorPolicy.hpp"
  29 #include "gc/shared/gcLocker.inline.hpp"
  30 #include "gc/shared/gcPolicyCounters.hpp"
  31 #include "gc/shared/genCollectedHeap.hpp"
  32 #include "gc/shared/generationSpec.hpp"
  33 #include "gc/shared/space.hpp"
  34 #include "gc/shared/vmGCOperations.hpp"
  35 #include "logging/log.hpp"
  36 #include "memory/universe.hpp"
  37 #include "runtime/arguments.hpp"
  38 #include "runtime/globals_extension.hpp"
  39 #include "runtime/handles.inline.hpp"
  40 #include "runtime/java.hpp"
  41 #include "runtime/thread.inline.hpp"
  42 #include "runtime/vmThread.hpp"
  43 #include "utilities/align.hpp"
  44 #include "utilities/macros.hpp"
  45 
  46 // CollectorPolicy methods
  47 
  48 CollectorPolicy::CollectorPolicy() :
  49     _space_alignment(0),
  50     _heap_alignment(0),
  51     _initial_heap_byte_size(InitialHeapSize),
  52     _max_heap_byte_size(MaxHeapSize),
  53     _min_heap_byte_size(Arguments::min_heap_size()),
  54     _should_clear_all_soft_refs(false),
  55     _all_soft_refs_clear(false)
  56 {}
  57 
  58 #ifdef ASSERT
  59 void CollectorPolicy::assert_flags() {
  60   assert(InitialHeapSize <= MaxHeapSize, "Ergonomics decided on incompatible initial and maximum heap sizes");
  61   assert(InitialHeapSize % _heap_alignment == 0, "InitialHeapSize alignment");
  62   assert(MaxHeapSize % _heap_alignment == 0, "MaxHeapSize alignment");
  63 }
  64 
  65 void CollectorPolicy::assert_size_info() {
  66   assert(InitialHeapSize == _initial_heap_byte_size, "Discrepancy between InitialHeapSize flag and local storage");
  67   assert(MaxHeapSize == _max_heap_byte_size, "Discrepancy between MaxHeapSize flag and local storage");
  68   assert(_max_heap_byte_size >= _min_heap_byte_size, "Ergonomics decided on incompatible minimum and maximum heap sizes");
  69   assert(_initial_heap_byte_size >= _min_heap_byte_size, "Ergonomics decided on incompatible initial and minimum heap sizes");
  70   assert(_max_heap_byte_size >= _initial_heap_byte_size, "Ergonomics decided on incompatible initial and maximum heap sizes");
  71   assert(_min_heap_byte_size % _heap_alignment == 0, "min_heap_byte_size alignment");
  72   assert(_initial_heap_byte_size % _heap_alignment == 0, "initial_heap_byte_size alignment");
  73   assert(_max_heap_byte_size % _heap_alignment == 0, "max_heap_byte_size alignment");
  74 }
  75 #endif // ASSERT
  76 
  77 void CollectorPolicy::initialize_flags() {
  78   assert(_space_alignment != 0, "Space alignment not set up properly");
  79   assert(_heap_alignment != 0, "Heap alignment not set up properly");
  80   assert(_heap_alignment >= _space_alignment,
  81          "heap_alignment: " SIZE_FORMAT " less than space_alignment: " SIZE_FORMAT,
  82          _heap_alignment, _space_alignment);
  83   assert(_heap_alignment % _space_alignment == 0,
  84          "heap_alignment: " SIZE_FORMAT " not aligned by space_alignment: " SIZE_FORMAT,
  85          _heap_alignment, _space_alignment);
  86 
  87   if (FLAG_IS_CMDLINE(MaxHeapSize)) {
  88     if (FLAG_IS_CMDLINE(InitialHeapSize) && InitialHeapSize > MaxHeapSize) {
  89       vm_exit_during_initialization("Initial heap size set to a larger value than the maximum heap size");
  90     }
  91     if (_min_heap_byte_size != 0 && MaxHeapSize < _min_heap_byte_size) {
  92       vm_exit_during_initialization("Incompatible minimum and maximum heap sizes specified");
  93     }
  94   }
  95 
  96   // Check heap parameter properties
  97   if (MaxHeapSize < 2 * M) {
  98     vm_exit_during_initialization("Too small maximum heap");
  99   }
 100   if (InitialHeapSize < M) {
 101     vm_exit_during_initialization("Too small initial heap");
 102   }
 103   if (_min_heap_byte_size < M) {
 104     vm_exit_during_initialization("Too small minimum heap");
 105   }
 106 
 107   // User inputs from -Xmx and -Xms must be aligned
 108   _min_heap_byte_size = align_up(_min_heap_byte_size, _heap_alignment);
 109   size_t aligned_initial_heap_size = align_up(InitialHeapSize, _heap_alignment);
 110   size_t aligned_max_heap_size = align_up(MaxHeapSize, _heap_alignment);
 111 
 112   // Write back to flags if the values changed
 113   if (aligned_initial_heap_size != InitialHeapSize) {
 114     FLAG_SET_ERGO(size_t, InitialHeapSize, aligned_initial_heap_size);
 115   }
 116   if (aligned_max_heap_size != MaxHeapSize) {
 117     FLAG_SET_ERGO(size_t, MaxHeapSize, aligned_max_heap_size);
 118   }
 119 
 120   if (FLAG_IS_CMDLINE(InitialHeapSize) && _min_heap_byte_size != 0 &&
 121       InitialHeapSize < _min_heap_byte_size) {
 122     vm_exit_during_initialization("Incompatible minimum and initial heap sizes specified");
 123   }
 124   if (!FLAG_IS_DEFAULT(InitialHeapSize) && InitialHeapSize > MaxHeapSize) {
 125     FLAG_SET_ERGO(size_t, MaxHeapSize, InitialHeapSize);
 126   } else if (!FLAG_IS_DEFAULT(MaxHeapSize) && InitialHeapSize > MaxHeapSize) {
 127     FLAG_SET_ERGO(size_t, InitialHeapSize, MaxHeapSize);
 128     if (InitialHeapSize < _min_heap_byte_size) {
 129       _min_heap_byte_size = InitialHeapSize;
 130     }
 131   }
 132 
 133   _initial_heap_byte_size = InitialHeapSize;
 134   _max_heap_byte_size = MaxHeapSize;
 135 
 136   FLAG_SET_ERGO(size_t, MinHeapDeltaBytes, align_up(MinHeapDeltaBytes, _space_alignment));
 137 
 138   DEBUG_ONLY(CollectorPolicy::assert_flags();)
 139 }
 140 
 141 void CollectorPolicy::initialize_size_info() {
 142   log_debug(gc, heap)("Minimum heap " SIZE_FORMAT "  Initial heap " SIZE_FORMAT "  Maximum heap " SIZE_FORMAT,
 143                       _min_heap_byte_size, _initial_heap_byte_size, _max_heap_byte_size);
 144 
 145   DEBUG_ONLY(CollectorPolicy::assert_size_info();)
 146 }
 147 
 148 bool CollectorPolicy::use_should_clear_all_soft_refs(bool v) {
 149   bool result = _should_clear_all_soft_refs;
 150   set_should_clear_all_soft_refs(false);
 151   return result;
 152 }
 153 
 154 CardTableRS* CollectorPolicy::create_rem_set(MemRegion whole_heap) {
 155   return new CardTableRS(whole_heap);
 156 }
 157 
 158 void CollectorPolicy::cleared_all_soft_refs() {
 159   _all_soft_refs_clear = true;
 160 }
 161 
 162 size_t CollectorPolicy::compute_heap_alignment() {
 163   // The card marking array and the offset arrays for old generations are
 164   // committed in os pages as well. Make sure they are entirely full (to
 165   // avoid partial page problems), e.g. if 512 bytes heap corresponds to 1
 166   // byte entry and the os page size is 4096, the maximum heap size should
 167   // be 512*4096 = 2MB aligned.
 168 
 169   size_t alignment = CardTableRS::ct_max_alignment_constraint();
 170 
 171   if (UseLargePages) {
 172       // In presence of large pages we have to make sure that our
 173       // alignment is large page aware.
 174       alignment = lcm(os::large_page_size(), alignment);
 175   }
 176 
 177   return alignment;
 178 }
 179 
 180 // GenCollectorPolicy methods
 181 
 182 GenCollectorPolicy::GenCollectorPolicy() :
 183     _min_young_size(0),
 184     _initial_young_size(0),
 185     _max_young_size(0),
 186     _min_old_size(0),
 187     _initial_old_size(0),
 188     _max_old_size(0),
 189     _gen_alignment(0),
 190     _young_gen_spec(NULL),
 191     _old_gen_spec(NULL),
 192     _size_policy(NULL)
 193 {}
 194 
 195 size_t GenCollectorPolicy::scale_by_NewRatio_aligned(size_t base_size) {
 196   return align_down_bounded(base_size / (NewRatio + 1), _gen_alignment);
 197 }
 198 
 199 size_t GenCollectorPolicy::bound_minus_alignment(size_t desired_size,
 200                                                  size_t maximum_size) {
 201   size_t max_minus = maximum_size - _gen_alignment;
 202   return desired_size < max_minus ? desired_size : max_minus;
 203 }
 204 
 205 
 206 void GenCollectorPolicy::initialize_size_policy(size_t init_eden_size,
 207                                                 size_t init_promo_size,
 208                                                 size_t init_survivor_size) {
 209   const double max_gc_pause_sec = ((double) MaxGCPauseMillis) / 1000.0;
 210   _size_policy = new AdaptiveSizePolicy(init_eden_size,
 211                                         init_promo_size,
 212                                         init_survivor_size,
 213                                         max_gc_pause_sec,
 214                                         GCTimeRatio);
 215 }
 216 
 217 void GenCollectorPolicy::cleared_all_soft_refs() {
 218   // If near gc overhear limit, continue to clear SoftRefs.  SoftRefs may
 219   // have been cleared in the last collection but if the gc overhear
 220   // limit continues to be near, SoftRefs should still be cleared.
 221   if (size_policy() != NULL) {
 222     _should_clear_all_soft_refs = size_policy()->gc_overhead_limit_near();
 223   }
 224 
 225   CollectorPolicy::cleared_all_soft_refs();
 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_up(3 * _space_alignment, _gen_alignment);
 231 }
 232 
 233 size_t GenCollectorPolicy::old_gen_size_lower_bound() {
 234   return align_up(_space_alignment, _gen_alignment);
 235 }
 236 
 237 #ifdef ASSERT
 238 void GenCollectorPolicy::assert_flags() {
 239   CollectorPolicy::assert_flags();
 240   assert(NewSize >= _min_young_size, "Ergonomics decided on a too small young gen size");
 241   assert(NewSize <= MaxNewSize, "Ergonomics decided on incompatible initial and maximum young gen sizes");
 242   assert(FLAG_IS_DEFAULT(MaxNewSize) || MaxNewSize < MaxHeapSize, "Ergonomics decided on incompatible maximum young gen and heap sizes");
 243   assert(NewSize % _gen_alignment == 0, "NewSize alignment");
 244   assert(FLAG_IS_DEFAULT(MaxNewSize) || MaxNewSize % _gen_alignment == 0, "MaxNewSize alignment");
 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_young_size, "Discrepancy between NewSize flag and local storage");
 254   assert(MaxNewSize == _max_young_size, "Discrepancy between MaxNewSize flag and local storage");
 255   assert(OldSize == _initial_old_size, "Discrepancy between OldSize flag and local storage");
 256   assert(_min_young_size <= _initial_young_size, "Ergonomics decided on incompatible minimum and initial young gen sizes");
 257   assert(_initial_young_size <= _max_young_size, "Ergonomics decided on incompatible initial and maximum young gen sizes");
 258   assert(_min_young_size % _gen_alignment == 0, "_min_young_size alignment");
 259   assert(_initial_young_size % _gen_alignment == 0, "_initial_young_size alignment");
 260   assert(_max_young_size % _gen_alignment == 0, "_max_young_size alignment");
 261   assert(_min_young_size <= bound_minus_alignment(_min_young_size, _min_heap_byte_size),
 262       "Ergonomics made minimum young generation larger than minimum heap");
 263   assert(_initial_young_size <=  bound_minus_alignment(_initial_young_size, _initial_heap_byte_size),
 264       "Ergonomics made initial young generation larger than initial heap");
 265   assert(_max_young_size <= bound_minus_alignment(_max_young_size, _max_heap_byte_size),
 266       "Ergonomics made maximum young generation lager than maximum heap");
 267   assert(_min_old_size <= _initial_old_size, "Ergonomics decided on incompatible minimum and initial old gen sizes");
 268   assert(_initial_old_size <= _max_old_size, "Ergonomics decided on incompatible initial and maximum old gen sizes");
 269   assert(_max_old_size % _gen_alignment == 0, "_max_old_size alignment");
 270   assert(_initial_old_size % _gen_alignment == 0, "_initial_old_size alignment");
 271   assert(_max_heap_byte_size <= (_max_young_size + _max_old_size), "Total maximum heap sizes must be sum of generation maximum sizes");
 272   assert(_min_young_size + _min_old_size <= _min_heap_byte_size, "Minimum generation sizes exceed minimum heap size");
 273   assert(_initial_young_size + _initial_old_size == _initial_heap_byte_size, "Initial generation sizes should match initial heap size");
 274   assert(_max_young_size + _max_old_size == _max_heap_byte_size, "Maximum generation sizes should match maximum heap size");
 275 }
 276 #endif // ASSERT
 277 
 278 void GenCollectorPolicy::initialize_flags() {
 279   CollectorPolicy::initialize_flags();
 280 
 281   assert(_gen_alignment != 0, "Generation alignment not set up properly");
 282   assert(_heap_alignment >= _gen_alignment,
 283          "heap_alignment: " SIZE_FORMAT " less than gen_alignment: " SIZE_FORMAT,
 284          _heap_alignment, _gen_alignment);
 285   assert(_gen_alignment % _space_alignment == 0,
 286          "gen_alignment: " SIZE_FORMAT " not aligned by space_alignment: " SIZE_FORMAT,
 287          _gen_alignment, _space_alignment);
 288   assert(_heap_alignment % _gen_alignment == 0,
 289          "heap_alignment: " SIZE_FORMAT " not aligned by gen_alignment: " SIZE_FORMAT,
 290          _heap_alignment, _gen_alignment);
 291 
 292   // All generational heaps have a young gen; handle those flags here
 293 
 294   // Make sure the heap is large enough for two generations
 295   size_t smallest_new_size = young_gen_size_lower_bound();
 296   size_t smallest_heap_size = align_up(smallest_new_size + old_gen_size_lower_bound(),
 297                                            _heap_alignment);
 298   if (MaxHeapSize < smallest_heap_size) {
 299     FLAG_SET_ERGO(size_t, MaxHeapSize, smallest_heap_size);
 300     _max_heap_byte_size = MaxHeapSize;
 301   }
 302   // If needed, synchronize _min_heap_byte size and _initial_heap_byte_size
 303   if (_min_heap_byte_size < smallest_heap_size) {
 304     _min_heap_byte_size = smallest_heap_size;
 305     if (InitialHeapSize < _min_heap_byte_size) {
 306       FLAG_SET_ERGO(size_t, InitialHeapSize, smallest_heap_size);
 307       _initial_heap_byte_size = smallest_heap_size;
 308     }
 309   }
 310 
 311   // Make sure NewSize allows an old generation to fit even if set on the command line
 312   if (FLAG_IS_CMDLINE(NewSize) && NewSize >= _initial_heap_byte_size) {
 313     log_warning(gc, ergo)("NewSize was set larger than initial heap size, will use initial heap size.");
 314     FLAG_SET_ERGO(size_t, NewSize, bound_minus_alignment(NewSize, _initial_heap_byte_size));
 315   }
 316 
 317   // Now take the actual NewSize into account. We will silently increase NewSize
 318   // if the user specified a smaller or unaligned value.
 319   size_t bounded_new_size = bound_minus_alignment(NewSize, MaxHeapSize);
 320   bounded_new_size = MAX2(smallest_new_size, align_down(bounded_new_size, _gen_alignment));
 321   if (bounded_new_size != NewSize) {
 322     FLAG_SET_ERGO(size_t, NewSize, bounded_new_size);
 323   }
 324   _min_young_size = smallest_new_size;
 325   _initial_young_size = NewSize;
 326 
 327   if (!FLAG_IS_DEFAULT(MaxNewSize)) {
 328     if (MaxNewSize >= MaxHeapSize) {
 329       // Make sure there is room for an old generation
 330       size_t smaller_max_new_size = MaxHeapSize - _gen_alignment;
 331       if (FLAG_IS_CMDLINE(MaxNewSize)) {
 332         log_warning(gc, ergo)("MaxNewSize (" SIZE_FORMAT "k) is equal to or greater than the entire "
 333                               "heap (" SIZE_FORMAT "k).  A new max generation size of " SIZE_FORMAT "k will be used.",
 334                               MaxNewSize/K, MaxHeapSize/K, smaller_max_new_size/K);
 335       }
 336       FLAG_SET_ERGO(size_t, MaxNewSize, smaller_max_new_size);
 337       if (NewSize > MaxNewSize) {
 338         FLAG_SET_ERGO(size_t, NewSize, MaxNewSize);
 339         _initial_young_size = NewSize;
 340       }
 341     } else if (MaxNewSize < _initial_young_size) {
 342       FLAG_SET_ERGO(size_t, MaxNewSize, _initial_young_size);
 343     } else if (!is_aligned(MaxNewSize, _gen_alignment)) {
 344       FLAG_SET_ERGO(size_t, MaxNewSize, align_down(MaxNewSize, _gen_alignment));
 345     }
 346     _max_young_size = MaxNewSize;
 347   }
 348 
 349   if (NewSize > MaxNewSize) {
 350     // At this point this should only happen if the user specifies a large NewSize and/or
 351     // a small (but not too small) MaxNewSize.
 352     if (FLAG_IS_CMDLINE(MaxNewSize)) {
 353       log_warning(gc, ergo)("NewSize (" SIZE_FORMAT "k) is greater than the MaxNewSize (" SIZE_FORMAT "k). "
 354                             "A new max generation size of " SIZE_FORMAT "k will be used.",
 355                             NewSize/K, MaxNewSize/K, NewSize/K);
 356     }
 357     FLAG_SET_ERGO(size_t, MaxNewSize, NewSize);
 358     _max_young_size = MaxNewSize;
 359   }
 360 
 361   if (SurvivorRatio < 1 || NewRatio < 1) {
 362     vm_exit_during_initialization("Invalid young gen ratio specified");
 363   }
 364 
 365   if (OldSize < old_gen_size_lower_bound()) {
 366     FLAG_SET_ERGO(size_t, OldSize, old_gen_size_lower_bound());
 367   }
 368   if (!is_aligned(OldSize, _gen_alignment)) {
 369     FLAG_SET_ERGO(size_t, OldSize, align_down(OldSize, _gen_alignment));
 370   }
 371 
 372   if (FLAG_IS_CMDLINE(OldSize) && FLAG_IS_DEFAULT(MaxHeapSize)) {
 373     // NewRatio will be used later to set the young generation size so we use
 374     // it to calculate how big the heap should be based on the requested OldSize
 375     // and NewRatio.
 376     assert(NewRatio > 0, "NewRatio should have been set up earlier");
 377     size_t calculated_heapsize = (OldSize / NewRatio) * (NewRatio + 1);
 378 
 379     calculated_heapsize = align_up(calculated_heapsize, _heap_alignment);
 380     FLAG_SET_ERGO(size_t, MaxHeapSize, calculated_heapsize);
 381     _max_heap_byte_size = MaxHeapSize;
 382     FLAG_SET_ERGO(size_t, InitialHeapSize, calculated_heapsize);
 383     _initial_heap_byte_size = InitialHeapSize;
 384   }
 385 
 386   // Adjust NewSize and OldSize or MaxHeapSize to match each other
 387   if (NewSize + OldSize > MaxHeapSize) {
 388     if (FLAG_IS_CMDLINE(MaxHeapSize)) {
 389       // Somebody has set a maximum heap size with the intention that we should not
 390       // exceed it. Adjust New/OldSize as necessary.
 391       size_t calculated_size = NewSize + OldSize;
 392       double shrink_factor = (double) MaxHeapSize / calculated_size;
 393       size_t smaller_new_size = align_down((size_t)(NewSize * shrink_factor), _gen_alignment);
 394       FLAG_SET_ERGO(size_t, NewSize, MAX2(young_gen_size_lower_bound(), smaller_new_size));
 395       _initial_young_size = NewSize;
 396 
 397       // OldSize is already aligned because above we aligned MaxHeapSize to
 398       // _heap_alignment, and we just made sure that NewSize is aligned to
 399       // _gen_alignment. In initialize_flags() we verified that _heap_alignment
 400       // is a multiple of _gen_alignment.
 401       FLAG_SET_ERGO(size_t, OldSize, MaxHeapSize - NewSize);
 402     } else {
 403       FLAG_SET_ERGO(size_t, MaxHeapSize, align_up(NewSize + OldSize, _heap_alignment));
 404       _max_heap_byte_size = MaxHeapSize;
 405     }
 406   }
 407 
 408   // Update NewSize, if possible, to avoid sizing the young gen too small when only
 409   // OldSize is set on the command line.
 410   if (FLAG_IS_CMDLINE(OldSize) && !FLAG_IS_CMDLINE(NewSize)) {
 411     if (OldSize < _initial_heap_byte_size) {
 412       size_t new_size = _initial_heap_byte_size - OldSize;
 413       // Need to compare against the flag value for max since _max_young_size
 414       // might not have been set yet.
 415       if (new_size >= _min_young_size && new_size <= MaxNewSize) {
 416         FLAG_SET_ERGO(size_t, NewSize, new_size);
 417         _initial_young_size = NewSize;
 418       }
 419     }
 420   }
 421 
 422   always_do_update_barrier = UseConcMarkSweepGC;
 423 
 424   DEBUG_ONLY(GenCollectorPolicy::assert_flags();)
 425 }
 426 
 427 // Values set on the command line win over any ergonomically
 428 // set command line parameters.
 429 // Ergonomic choice of parameters are done before this
 430 // method is called.  Values for command line parameters such as NewSize
 431 // and MaxNewSize feed those ergonomic choices into this method.
 432 // This method makes the final generation sizings consistent with
 433 // themselves and with overall heap sizings.
 434 // In the absence of explicitly set command line flags, policies
 435 // such as the use of NewRatio are used to size the generation.
 436 
 437 // Minimum sizes of the generations may be different than
 438 // the initial sizes.  An inconsistency is permitted here
 439 // in the total size that can be specified explicitly by
 440 // command line specification of OldSize and NewSize and
 441 // also a command line specification of -Xms.  Issue a warning
 442 // but allow the values to pass.
 443 void GenCollectorPolicy::initialize_size_info() {
 444   CollectorPolicy::initialize_size_info();
 445 
 446   _initial_young_size = NewSize;
 447   _max_young_size = MaxNewSize;
 448   _initial_old_size = OldSize;
 449 
 450   // Determine maximum size of the young generation.
 451 
 452   if (FLAG_IS_DEFAULT(MaxNewSize)) {
 453     _max_young_size = scale_by_NewRatio_aligned(_max_heap_byte_size);
 454     // Bound the maximum size by NewSize below (since it historically
 455     // would have been NewSize and because the NewRatio calculation could
 456     // yield a size that is too small) and bound it by MaxNewSize above.
 457     // Ergonomics plays here by previously calculating the desired
 458     // NewSize and MaxNewSize.
 459     _max_young_size = MIN2(MAX2(_max_young_size, _initial_young_size), MaxNewSize);
 460   }
 461 
 462   // Given the maximum young size, determine the initial and
 463   // minimum young sizes.
 464 
 465   if (_max_heap_byte_size == _initial_heap_byte_size) {
 466     // The maximum and initial heap sizes are the same so the generation's
 467     // initial size must be the same as it maximum size. Use NewSize as the
 468     // size if set on command line.
 469     _max_young_size = FLAG_IS_CMDLINE(NewSize) ? NewSize : _max_young_size;
 470     _initial_young_size = _max_young_size;
 471 
 472     // Also update the minimum size if min == initial == max.
 473     if (_max_heap_byte_size == _min_heap_byte_size) {
 474       _min_young_size = _max_young_size;
 475     }
 476   } else {
 477     if (FLAG_IS_CMDLINE(NewSize)) {
 478       // If NewSize is set on the command line, we should use it as
 479       // the initial size, but make sure it is within the heap bounds.
 480       _initial_young_size =
 481         MIN2(_max_young_size, bound_minus_alignment(NewSize, _initial_heap_byte_size));
 482       _min_young_size = bound_minus_alignment(_initial_young_size, _min_heap_byte_size);
 483     } else {
 484       // For the case where NewSize is not set on the command line, use
 485       // NewRatio to size the initial generation size. Use the current
 486       // NewSize as the floor, because if NewRatio is overly large, the resulting
 487       // size can be too small.
 488       _initial_young_size =
 489         MIN2(_max_young_size, MAX2(scale_by_NewRatio_aligned(_initial_heap_byte_size), NewSize));
 490     }
 491   }
 492 
 493   log_trace(gc, heap)("1: Minimum young " SIZE_FORMAT "  Initial young " SIZE_FORMAT "  Maximum young " SIZE_FORMAT,
 494                       _min_young_size, _initial_young_size, _max_young_size);
 495 
 496   // At this point the minimum, initial and maximum sizes
 497   // of the overall heap and of the young generation have been determined.
 498   // The maximum old size can be determined from the maximum young
 499   // and maximum heap size since no explicit flags exist
 500   // for setting the old generation maximum.
 501   _max_old_size = MAX2(_max_heap_byte_size - _max_young_size, _gen_alignment);
 502 
 503   // If no explicit command line flag has been set for the
 504   // old generation size, use what is left.
 505   if (!FLAG_IS_CMDLINE(OldSize)) {
 506     // The user has not specified any value but the ergonomics
 507     // may have chosen a value (which may or may not be consistent
 508     // with the overall heap size).  In either case make
 509     // the minimum, maximum and initial sizes consistent
 510     // with the young sizes and the overall heap sizes.
 511     _min_old_size = _gen_alignment;
 512     _initial_old_size = MIN2(_max_old_size, MAX2(_initial_heap_byte_size - _initial_young_size, _min_old_size));
 513     // _max_old_size has already been made consistent above.
 514   } else {
 515     // OldSize has been explicitly set on the command line. Use it
 516     // for the initial size but make sure the minimum allow a young
 517     // generation to fit as well.
 518     // If the user has explicitly set an OldSize that is inconsistent
 519     // with other command line flags, issue a warning.
 520     // The generation minimums and the overall heap minimum should
 521     // be within one generation alignment.
 522     if (_initial_old_size > _max_old_size) {
 523       log_warning(gc, ergo)("Inconsistency between maximum heap size and maximum "
 524                             "generation sizes: using maximum heap = " SIZE_FORMAT
 525                             ", -XX:OldSize flag is being ignored",
 526                             _max_heap_byte_size);
 527       _initial_old_size = _max_old_size;
 528     }
 529 
 530     _min_old_size = MIN2(_initial_old_size, _min_heap_byte_size - _min_young_size);
 531   }
 532 
 533   // The initial generation sizes should match the initial heap size,
 534   // if not issue a warning and resize the generations. This behavior
 535   // differs from JDK8 where the generation sizes have higher priority
 536   // than the initial heap size.
 537   if ((_initial_old_size + _initial_young_size) != _initial_heap_byte_size) {
 538     log_warning(gc, ergo)("Inconsistency between generation sizes and heap size, resizing "
 539                           "the generations to fit the heap.");
 540 
 541     size_t desired_young_size = _initial_heap_byte_size - _initial_old_size;
 542     if (_initial_heap_byte_size < _initial_old_size) {
 543       // Old want all memory, use minimum for young and rest for old
 544       _initial_young_size = _min_young_size;
 545       _initial_old_size = _initial_heap_byte_size - _min_young_size;
 546     } else if (desired_young_size > _max_young_size) {
 547       // Need to increase both young and old generation
 548       _initial_young_size = _max_young_size;
 549       _initial_old_size = _initial_heap_byte_size - _max_young_size;
 550     } else if (desired_young_size < _min_young_size) {
 551       // Need to decrease both young and old generation
 552       _initial_young_size = _min_young_size;
 553       _initial_old_size = _initial_heap_byte_size - _min_young_size;
 554     } else {
 555       // The young generation boundaries allow us to only update the
 556       // young generation.
 557       _initial_young_size = desired_young_size;
 558     }
 559 
 560     log_trace(gc, heap)("2: Minimum young " SIZE_FORMAT "  Initial young " SIZE_FORMAT "  Maximum young " SIZE_FORMAT,
 561                     _min_young_size, _initial_young_size, _max_young_size);
 562   }
 563 
 564   // Write back to flags if necessary.
 565   if (NewSize != _initial_young_size) {
 566     FLAG_SET_ERGO(size_t, NewSize, _initial_young_size);
 567   }
 568 
 569   if (MaxNewSize != _max_young_size) {
 570     FLAG_SET_ERGO(size_t, MaxNewSize, _max_young_size);
 571   }
 572 
 573   if (OldSize != _initial_old_size) {
 574     FLAG_SET_ERGO(size_t, OldSize, _initial_old_size);
 575   }
 576 
 577   log_trace(gc, heap)("Minimum old " SIZE_FORMAT "  Initial old " SIZE_FORMAT "  Maximum old " SIZE_FORMAT,
 578                   _min_old_size, _initial_old_size, _max_old_size);
 579 
 580   DEBUG_ONLY(GenCollectorPolicy::assert_size_info();)
 581 }
 582 
 583 HeapWord* GenCollectorPolicy::mem_allocate_work(size_t size,
 584                                         bool is_tlab,
 585                                         bool* gc_overhead_limit_was_exceeded) {
 586   GenCollectedHeap *gch = GenCollectedHeap::heap();
 587 
 588   debug_only(gch->check_for_valid_allocation_state());
 589   assert(gch->no_gc_in_progress(), "Allocation during gc not allowed");
 590 
 591   // In general gc_overhead_limit_was_exceeded should be false so
 592   // set it so here and reset it to true only if the gc time
 593   // limit is being exceeded as checked below.
 594   *gc_overhead_limit_was_exceeded = false;
 595 
 596   HeapWord* result = NULL;
 597 
 598   // Loop until the allocation is satisfied, or unsatisfied after GC.
 599   for (uint try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) {
 600     HandleMark hm; // Discard any handles allocated in each iteration.
 601 
 602     // First allocation attempt is lock-free.
 603     Generation *young = gch->young_gen();
 604     assert(young->supports_inline_contig_alloc(),
 605       "Otherwise, must do alloc within heap lock");
 606     if (young->should_allocate(size, is_tlab)) {
 607       result = young->par_allocate(size, is_tlab);
 608       if (result != NULL) {
 609         assert(gch->is_in_reserved(result), "result not in heap");
 610         return result;
 611       }
 612     }
 613     uint gc_count_before;  // Read inside the Heap_lock locked region.
 614     {
 615       MutexLocker ml(Heap_lock);
 616       log_trace(gc, alloc)("GenCollectorPolicy::mem_allocate_work: attempting locked slow path allocation");
 617       // Note that only large objects get a shot at being
 618       // allocated in later generations.
 619       bool first_only = ! should_try_older_generation_allocation(size);
 620 
 621       result = gch->attempt_allocation(size, is_tlab, first_only);
 622       if (result != NULL) {
 623         assert(gch->is_in_reserved(result), "result not in heap");
 624         return result;
 625       }
 626 
 627       if (GCLocker::is_active_and_needs_gc()) {
 628         if (is_tlab) {
 629           return NULL;  // Caller will retry allocating individual object.
 630         }
 631         if (!gch->is_maximal_no_gc()) {
 632           // Try and expand heap to satisfy request.
 633           result = expand_heap_and_allocate(size, is_tlab);
 634           // Result could be null if we are out of space.
 635           if (result != NULL) {
 636             return result;
 637           }
 638         }
 639 
 640         if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
 641           return NULL; // We didn't get to do a GC and we didn't get any memory.
 642         }
 643 
 644         // If this thread is not in a jni critical section, we stall
 645         // the requestor until the critical section has cleared and
 646         // GC allowed. When the critical section clears, a GC is
 647         // initiated by the last thread exiting the critical section; so
 648         // we retry the allocation sequence from the beginning of the loop,
 649         // rather than causing more, now probably unnecessary, GC attempts.
 650         JavaThread* jthr = JavaThread::current();
 651         if (!jthr->in_critical()) {
 652           MutexUnlocker mul(Heap_lock);
 653           // Wait for JNI critical section to be exited
 654           GCLocker::stall_until_clear();
 655           gclocker_stalled_count += 1;
 656           continue;
 657         } else {
 658           if (CheckJNICalls) {
 659             fatal("Possible deadlock due to allocating while"
 660                   " in jni critical section");
 661           }
 662           return NULL;
 663         }
 664       }
 665 
 666       // Read the gc count while the heap lock is held.
 667       gc_count_before = gch->total_collections();
 668     }
 669 
 670     VM_GenCollectForAllocation op(size, is_tlab, gc_count_before);
 671     VMThread::execute(&op);
 672     if (op.prologue_succeeded()) {
 673       result = op.result();
 674       if (op.gc_locked()) {
 675          assert(result == NULL, "must be NULL if gc_locked() is true");
 676          continue;  // Retry and/or stall as necessary.
 677       }
 678 
 679       // Allocation has failed and a collection
 680       // has been done.  If the gc time limit was exceeded the
 681       // this time, return NULL so that an out-of-memory
 682       // will be thrown.  Clear gc_overhead_limit_exceeded
 683       // so that the overhead exceeded does not persist.
 684 
 685       const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
 686       const bool softrefs_clear = all_soft_refs_clear();
 687 
 688       if (limit_exceeded && softrefs_clear) {
 689         *gc_overhead_limit_was_exceeded = true;
 690         size_policy()->set_gc_overhead_limit_exceeded(false);
 691         if (op.result() != NULL) {
 692           CollectedHeap::fill_with_object(op.result(), size);
 693         }
 694         return NULL;
 695       }
 696       assert(result == NULL || gch->is_in_reserved(result),
 697              "result not in heap");
 698       return result;
 699     }
 700 
 701     // Give a warning if we seem to be looping forever.
 702     if ((QueuedAllocationWarningCount > 0) &&
 703         (try_count % QueuedAllocationWarningCount == 0)) {
 704           log_warning(gc, ergo)("GenCollectorPolicy::mem_allocate_work retries %d times,"
 705                                 " size=" SIZE_FORMAT " %s", try_count, size, is_tlab ? "(TLAB)" : "");
 706     }
 707   }
 708 }
 709 
 710 HeapWord* GenCollectorPolicy::expand_heap_and_allocate(size_t size,
 711                                                        bool   is_tlab) {
 712   GenCollectedHeap *gch = GenCollectedHeap::heap();
 713   HeapWord* result = NULL;
 714   Generation *old = gch->old_gen();
 715   if (old->should_allocate(size, is_tlab)) {
 716     result = old->expand_and_allocate(size, is_tlab);
 717   }
 718   if (result == NULL) {
 719     Generation *young = gch->young_gen();
 720     if (young->should_allocate(size, is_tlab)) {
 721       result = young->expand_and_allocate(size, is_tlab);
 722     }
 723   }
 724   assert(result == NULL || gch->is_in_reserved(result), "result not in heap");
 725   return result;
 726 }
 727 
 728 HeapWord* GenCollectorPolicy::satisfy_failed_allocation(size_t size,
 729                                                         bool   is_tlab) {
 730   GenCollectedHeap *gch = GenCollectedHeap::heap();
 731   GCCauseSetter x(gch, GCCause::_allocation_failure);
 732   HeapWord* result = NULL;
 733 
 734   assert(size != 0, "Precondition violated");
 735   if (GCLocker::is_active_and_needs_gc()) {
 736     // GC locker is active; instead of a collection we will attempt
 737     // to expand the heap, if there's room for expansion.
 738     if (!gch->is_maximal_no_gc()) {
 739       result = expand_heap_and_allocate(size, is_tlab);
 740     }
 741     return result;   // Could be null if we are out of space.
 742   } else if (!gch->incremental_collection_will_fail(false /* don't consult_young */)) {
 743     // Do an incremental collection.
 744     gch->do_collection(false,                     // full
 745                        false,                     // clear_all_soft_refs
 746                        size,                      // size
 747                        is_tlab,                   // is_tlab
 748                        GenCollectedHeap::OldGen); // max_generation
 749   } else {
 750     log_trace(gc)(" :: Trying full because partial may fail :: ");
 751     // Try a full collection; see delta for bug id 6266275
 752     // for the original code and why this has been simplified
 753     // with from-space allocation criteria modified and
 754     // such allocation moved out of the safepoint path.
 755     gch->do_collection(true,                      // full
 756                        false,                     // clear_all_soft_refs
 757                        size,                      // size
 758                        is_tlab,                   // is_tlab
 759                        GenCollectedHeap::OldGen); // max_generation
 760   }
 761 
 762   result = gch->attempt_allocation(size, is_tlab, false /*first_only*/);
 763 
 764   if (result != NULL) {
 765     assert(gch->is_in_reserved(result), "result not in heap");
 766     return result;
 767   }
 768 
 769   // OK, collection failed, try expansion.
 770   result = expand_heap_and_allocate(size, is_tlab);
 771   if (result != NULL) {
 772     return result;
 773   }
 774 
 775   // If we reach this point, we're really out of memory. Try every trick
 776   // we can to reclaim memory. Force collection of soft references. Force
 777   // a complete compaction of the heap. Any additional methods for finding
 778   // free memory should be here, especially if they are expensive. If this
 779   // attempt fails, an OOM exception will be thrown.
 780   {
 781     UIntFlagSetting flag_change(MarkSweepAlwaysCompactCount, 1); // Make sure the heap is fully compacted
 782 
 783     gch->do_collection(true,                      // full
 784                        true,                      // clear_all_soft_refs
 785                        size,                      // size
 786                        is_tlab,                   // is_tlab
 787                        GenCollectedHeap::OldGen); // max_generation
 788   }
 789 
 790   result = gch->attempt_allocation(size, is_tlab, false /* first_only */);
 791   if (result != NULL) {
 792     assert(gch->is_in_reserved(result), "result not in heap");
 793     return result;
 794   }
 795 
 796   assert(!should_clear_all_soft_refs(),
 797     "Flag should have been handled and cleared prior to this point");
 798 
 799   // What else?  We might try synchronous finalization later.  If the total
 800   // space available is large enough for the allocation, then a more
 801   // complete compaction phase than we've tried so far might be
 802   // appropriate.
 803   return NULL;
 804 }
 805 
 806 MetaWord* CollectorPolicy::satisfy_failed_metadata_allocation(
 807                                                  ClassLoaderData* loader_data,
 808                                                  size_t word_size,
 809                                                  Metaspace::MetadataType mdtype) {
 810   uint loop_count = 0;
 811   uint gc_count = 0;
 812   uint full_gc_count = 0;
 813 
 814   assert(!Heap_lock->owned_by_self(), "Should not be holding the Heap_lock");
 815 
 816   do {
 817     MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
 818     if (result != NULL) {
 819       return result;
 820     }
 821 
 822     if (GCLocker::is_active_and_needs_gc()) {
 823       // If the GCLocker is active, just expand and allocate.
 824       // If that does not succeed, wait if this thread is not
 825       // in a critical section itself.
 826       result =
 827         loader_data->metaspace_non_null()->expand_and_allocate(word_size,
 828                                                                mdtype);
 829       if (result != NULL) {
 830         return result;
 831       }
 832       JavaThread* jthr = JavaThread::current();
 833       if (!jthr->in_critical()) {
 834         // Wait for JNI critical section to be exited
 835         GCLocker::stall_until_clear();
 836         // The GC invoked by the last thread leaving the critical
 837         // section will be a young collection and a full collection
 838         // is (currently) needed for unloading classes so continue
 839         // to the next iteration to get a full GC.
 840         continue;
 841       } else {
 842         if (CheckJNICalls) {
 843           fatal("Possible deadlock due to allocating while"
 844                 " in jni critical section");
 845         }
 846         return NULL;
 847       }
 848     }
 849 
 850     {  // Need lock to get self consistent gc_count's
 851       MutexLocker ml(Heap_lock);
 852       gc_count      = Universe::heap()->total_collections();
 853       full_gc_count = Universe::heap()->total_full_collections();
 854     }
 855 
 856     // Generate a VM operation
 857     VM_CollectForMetadataAllocation op(loader_data,
 858                                        word_size,
 859                                        mdtype,
 860                                        gc_count,
 861                                        full_gc_count,
 862                                        GCCause::_metadata_GC_threshold);
 863     VMThread::execute(&op);
 864 
 865     // If GC was locked out, try again. Check before checking success because the
 866     // prologue could have succeeded and the GC still have been locked out.
 867     if (op.gc_locked()) {
 868       continue;
 869     }
 870 
 871     if (op.prologue_succeeded()) {
 872       return op.result();
 873     }
 874     loop_count++;
 875     if ((QueuedAllocationWarningCount > 0) &&
 876         (loop_count % QueuedAllocationWarningCount == 0)) {
 877       log_warning(gc, ergo)("satisfy_failed_metadata_allocation() retries %d times,"
 878                             " size=" SIZE_FORMAT, loop_count, word_size);
 879     }
 880   } while (true);  // Until a GC is done
 881 }
 882 
 883 // Return true if any of the following is true:
 884 // . the allocation won't fit into the current young gen heap
 885 // . gc locker is occupied (jni critical section)
 886 // . heap memory is tight -- the most recent previous collection
 887 //   was a full collection because a partial collection (would
 888 //   have) failed and is likely to fail again
 889 bool GenCollectorPolicy::should_try_older_generation_allocation(
 890         size_t word_size) const {
 891   GenCollectedHeap* gch = GenCollectedHeap::heap();
 892   size_t young_capacity = gch->young_gen()->capacity_before_gc();
 893   return    (word_size > heap_word_size(young_capacity))
 894          || GCLocker::is_active_and_needs_gc()
 895          || gch->incremental_collection_failed();
 896 }
 897 
 898 
 899 //
 900 // MarkSweepPolicy methods
 901 //
 902 
 903 void MarkSweepPolicy::initialize_alignments() {
 904   _space_alignment = _gen_alignment = (size_t)Generation::GenGrain;
 905   _heap_alignment = compute_heap_alignment();
 906 }
 907 
 908 void MarkSweepPolicy::initialize_generations() {
 909   _young_gen_spec = new GenerationSpec(Generation::DefNew, _initial_young_size, _max_young_size, _gen_alignment);
 910   _old_gen_spec   = new GenerationSpec(Generation::MarkSweepCompact, _initial_old_size, _max_old_size, _gen_alignment);
 911 }
 912 
 913 void MarkSweepPolicy::initialize_gc_policy_counters() {
 914   // Initialize the policy counters - 2 collectors, 3 generations.
 915   _gc_policy_counters = new GCPolicyCounters("Copy:MSC", 2, 3);
 916 }
 917