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