1 /*
   2  * Copyright (c) 2000, 2019, 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 "aot/aotLoader.hpp"
  27 #include "classfile/classLoaderDataGraph.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/stringTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "gc/serial/defNewGeneration.hpp"
  35 #include "gc/shared/adaptiveSizePolicy.hpp"
  36 #include "gc/shared/cardTableBarrierSet.hpp"
  37 #include "gc/shared/cardTableRS.hpp"
  38 #include "gc/shared/collectedHeap.inline.hpp"
  39 #include "gc/shared/collectorCounters.hpp"
  40 #include "gc/shared/gcId.hpp"
  41 #include "gc/shared/gcLocker.hpp"
  42 #include "gc/shared/gcPolicyCounters.hpp"
  43 #include "gc/shared/gcTrace.hpp"
  44 #include "gc/shared/gcTraceTime.inline.hpp"
  45 #include "gc/shared/gcVMOperations.hpp"
  46 #include "gc/shared/genCollectedHeap.hpp"
  47 #include "gc/shared/genOopClosures.inline.hpp"
  48 #include "gc/shared/generationSpec.hpp"
  49 #include "gc/shared/oopStorageParState.inline.hpp"
  50 #include "gc/shared/scavengableNMethods.hpp"
  51 #include "gc/shared/space.hpp"
  52 #include "gc/shared/strongRootsScope.hpp"
  53 #include "gc/shared/weakProcessor.hpp"
  54 #include "gc/shared/workgroup.hpp"
  55 #include "memory/filemap.hpp"
  56 #include "memory/metaspaceCounters.hpp"
  57 #include "memory/resourceArea.hpp"
  58 #include "oops/oop.inline.hpp"
  59 #include "runtime/biasedLocking.hpp"
  60 #include "runtime/flags/flagSetting.hpp"
  61 #include "runtime/handles.hpp"
  62 #include "runtime/handles.inline.hpp"
  63 #include "runtime/java.hpp"
  64 #include "runtime/vmThread.hpp"
  65 #include "services/management.hpp"
  66 #include "services/memoryService.hpp"
  67 #include "utilities/debug.hpp"
  68 #include "utilities/formatBuffer.hpp"
  69 #include "utilities/macros.hpp"
  70 #include "utilities/stack.inline.hpp"
  71 #include "utilities/vmError.hpp"
  72 #if INCLUDE_JVMCI
  73 #include "jvmci/jvmci.hpp"
  74 #endif
  75 
  76 GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy,
  77                                    Generation::Name young,
  78                                    Generation::Name old,
  79                                    const char* policy_counters_name) :
  80   CollectedHeap(),
  81   _young_gen_spec(new GenerationSpec(young,
  82                                      policy->initial_young_size(),
  83                                      policy->max_young_size(),
  84                                      policy->gen_alignment())),
  85   _old_gen_spec(new GenerationSpec(old,
  86                                    policy->initial_old_size(),
  87                                    policy->max_old_size(),
  88                                    policy->gen_alignment())),
  89   _rem_set(NULL),
  90   _gen_policy(policy),
  91   _soft_ref_gen_policy(),
  92   _gc_policy_counters(new GCPolicyCounters(policy_counters_name, 2, 2)),
  93   _full_collections_completed(0),
  94   _process_strong_tasks(new SubTasksDone(GCH_PS_NumElements)) {
  95 }
  96 
  97 jint GenCollectedHeap::initialize() {
  98   // While there are no constraints in the GC code that HeapWordSize
  99   // be any particular value, there are multiple other areas in the
 100   // system which believe this to be true (e.g. oop->object_size in some
 101   // cases incorrectly returns the size in wordSize units rather than
 102   // HeapWordSize).
 103   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
 104 
 105   // Allocate space for the heap.
 106 
 107   char* heap_address;
 108   ReservedSpace heap_rs;
 109 
 110   size_t heap_alignment = collector_policy()->heap_alignment();
 111 
 112   heap_address = allocate(heap_alignment, &heap_rs);
 113 
 114   if (!heap_rs.is_reserved()) {
 115     vm_shutdown_during_initialization(
 116       "Could not reserve enough space for object heap");
 117     return JNI_ENOMEM;
 118   }
 119 
 120   initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*)(heap_rs.base() + heap_rs.size()));
 121 
 122   _rem_set = create_rem_set(reserved_region());
 123   _rem_set->initialize();
 124   CardTableBarrierSet *bs = new CardTableBarrierSet(_rem_set);
 125   bs->initialize();
 126   BarrierSet::set_barrier_set(bs);
 127 
 128   ReservedSpace young_rs = heap_rs.first_part(_young_gen_spec->max_size(), false, false);
 129   _young_gen = _young_gen_spec->init(young_rs, rem_set());
 130   heap_rs = heap_rs.last_part(_young_gen_spec->max_size());
 131 
 132   ReservedSpace old_rs = heap_rs.first_part(_old_gen_spec->max_size(), false, false);
 133   _old_gen = _old_gen_spec->init(old_rs, rem_set());
 134   clear_incremental_collection_failed();
 135 
 136   return JNI_OK;
 137 }
 138 
 139 CardTableRS* GenCollectedHeap::create_rem_set(const MemRegion& reserved_region) {
 140   return new CardTableRS(reserved_region, false /* scan_concurrently */);
 141 }
 142 
 143 void GenCollectedHeap::initialize_size_policy(size_t init_eden_size,
 144                                               size_t init_promo_size,
 145                                               size_t init_survivor_size) {
 146   const double max_gc_pause_sec = ((double) MaxGCPauseMillis) / 1000.0;
 147   _size_policy = new AdaptiveSizePolicy(init_eden_size,
 148                                         init_promo_size,
 149                                         init_survivor_size,
 150                                         max_gc_pause_sec,
 151                                         GCTimeRatio);
 152 }
 153 
 154 char* GenCollectedHeap::allocate(size_t alignment,
 155                                  ReservedSpace* heap_rs){
 156   // Now figure out the total size.
 157   const size_t pageSize = UseLargePages ? os::large_page_size() : os::vm_page_size();
 158   assert(alignment % pageSize == 0, "Must be");
 159 
 160   // Check for overflow.
 161   size_t total_reserved = _young_gen_spec->max_size() + _old_gen_spec->max_size();
 162   if (total_reserved < _young_gen_spec->max_size()) {
 163     vm_exit_during_initialization("The size of the object heap + VM data exceeds "
 164                                   "the maximum representable size");
 165   }
 166   assert(total_reserved % alignment == 0,
 167          "Gen size; total_reserved=" SIZE_FORMAT ", alignment="
 168          SIZE_FORMAT, total_reserved, alignment);
 169 
 170   *heap_rs = Universe::reserve_heap(total_reserved, alignment);
 171 
 172   os::trace_page_sizes("Heap",
 173                        collector_policy()->min_heap_byte_size(),
 174                        total_reserved,
 175                        alignment,
 176                        heap_rs->base(),
 177                        heap_rs->size());
 178 
 179   return heap_rs->base();
 180 }
 181 
 182 class GenIsScavengable : public BoolObjectClosure {
 183 public:
 184   bool do_object_b(oop obj) {
 185     return GenCollectedHeap::heap()->is_in_young(obj);
 186   }
 187 };
 188 
 189 static GenIsScavengable _is_scavengable;
 190 
 191 void GenCollectedHeap::post_initialize() {
 192   CollectedHeap::post_initialize();
 193   ref_processing_init();
 194 
 195   DefNewGeneration* def_new_gen = (DefNewGeneration*)_young_gen;
 196 
 197   initialize_size_policy(def_new_gen->eden()->capacity(),
 198                          _old_gen->capacity(),
 199                          def_new_gen->from()->capacity());
 200 
 201   MarkSweep::initialize();
 202 
 203   ScavengableNMethods::initialize(&_is_scavengable);
 204 }
 205 
 206 void GenCollectedHeap::ref_processing_init() {
 207   _young_gen->ref_processor_init();
 208   _old_gen->ref_processor_init();
 209 }
 210 
 211 GenerationSpec* GenCollectedHeap::young_gen_spec() const {
 212   return _young_gen_spec;
 213 }
 214 
 215 GenerationSpec* GenCollectedHeap::old_gen_spec() const {
 216   return _old_gen_spec;
 217 }
 218 
 219 size_t GenCollectedHeap::capacity() const {
 220   return _young_gen->capacity() + _old_gen->capacity();
 221 }
 222 
 223 size_t GenCollectedHeap::used() const {
 224   return _young_gen->used() + _old_gen->used();
 225 }
 226 
 227 void GenCollectedHeap::save_used_regions() {
 228   _old_gen->save_used_region();
 229   _young_gen->save_used_region();
 230 }
 231 
 232 size_t GenCollectedHeap::max_capacity() const {
 233   return _young_gen->max_capacity() + _old_gen->max_capacity();
 234 }
 235 
 236 // Update the _full_collections_completed counter
 237 // at the end of a stop-world full GC.
 238 unsigned int GenCollectedHeap::update_full_collections_completed() {
 239   MonitorLocker ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
 240   assert(_full_collections_completed <= _total_full_collections,
 241          "Can't complete more collections than were started");
 242   _full_collections_completed = _total_full_collections;
 243   ml.notify_all();
 244   return _full_collections_completed;
 245 }
 246 
 247 // Update the _full_collections_completed counter, as appropriate,
 248 // at the end of a concurrent GC cycle. Note the conditional update
 249 // below to allow this method to be called by a concurrent collector
 250 // without synchronizing in any manner with the VM thread (which
 251 // may already have initiated a STW full collection "concurrently").
 252 unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) {
 253   MonitorLocker ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
 254   assert((_full_collections_completed <= _total_full_collections) &&
 255          (count <= _total_full_collections),
 256          "Can't complete more collections than were started");
 257   if (count > _full_collections_completed) {
 258     _full_collections_completed = count;
 259     ml.notify_all();
 260   }
 261   return _full_collections_completed;
 262 }
 263 
 264 // Return true if any of the following is true:
 265 // . the allocation won't fit into the current young gen heap
 266 // . gc locker is occupied (jni critical section)
 267 // . heap memory is tight -- the most recent previous collection
 268 //   was a full collection because a partial collection (would
 269 //   have) failed and is likely to fail again
 270 bool GenCollectedHeap::should_try_older_generation_allocation(size_t word_size) const {
 271   size_t young_capacity = _young_gen->capacity_before_gc();
 272   return    (word_size > heap_word_size(young_capacity))
 273          || GCLocker::is_active_and_needs_gc()
 274          || incremental_collection_failed();
 275 }
 276 
 277 HeapWord* GenCollectedHeap::expand_heap_and_allocate(size_t size, bool   is_tlab) {
 278   HeapWord* result = NULL;
 279   if (_old_gen->should_allocate(size, is_tlab)) {
 280     result = _old_gen->expand_and_allocate(size, is_tlab);
 281   }
 282   if (result == NULL) {
 283     if (_young_gen->should_allocate(size, is_tlab)) {
 284       result = _young_gen->expand_and_allocate(size, is_tlab);
 285     }
 286   }
 287   assert(result == NULL || is_in_reserved(result), "result not in heap");
 288   return result;
 289 }
 290 
 291 HeapWord* GenCollectedHeap::mem_allocate_work(size_t size,
 292                                               bool is_tlab,
 293                                               bool* gc_overhead_limit_was_exceeded) {
 294   // In general gc_overhead_limit_was_exceeded should be false so
 295   // set it so here and reset it to true only if the gc time
 296   // limit is being exceeded as checked below.
 297   *gc_overhead_limit_was_exceeded = false;
 298 
 299   HeapWord* result = NULL;
 300 
 301   // Loop until the allocation is satisfied, or unsatisfied after GC.
 302   for (uint try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) {
 303     HandleMark hm; // Discard any handles allocated in each iteration.
 304 
 305     // First allocation attempt is lock-free.
 306     Generation *young = _young_gen;
 307     assert(young->supports_inline_contig_alloc(),
 308       "Otherwise, must do alloc within heap lock");
 309     if (young->should_allocate(size, is_tlab)) {
 310       result = young->par_allocate(size, is_tlab);
 311       if (result != NULL) {
 312         assert(is_in_reserved(result), "result not in heap");
 313         return result;
 314       }
 315     }
 316     uint gc_count_before;  // Read inside the Heap_lock locked region.
 317     {
 318       MutexLocker ml(Heap_lock);
 319       log_trace(gc, alloc)("GenCollectedHeap::mem_allocate_work: attempting locked slow path allocation");
 320       // Note that only large objects get a shot at being
 321       // allocated in later generations.
 322       bool first_only = !should_try_older_generation_allocation(size);
 323 
 324       result = attempt_allocation(size, is_tlab, first_only);
 325       if (result != NULL) {
 326         assert(is_in_reserved(result), "result not in heap");
 327         return result;
 328       }
 329 
 330       if (GCLocker::is_active_and_needs_gc()) {
 331         if (is_tlab) {
 332           return NULL;  // Caller will retry allocating individual object.
 333         }
 334         if (!is_maximal_no_gc()) {
 335           // Try and expand heap to satisfy request.
 336           result = expand_heap_and_allocate(size, is_tlab);
 337           // Result could be null if we are out of space.
 338           if (result != NULL) {
 339             return result;
 340           }
 341         }
 342 
 343         if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
 344           return NULL; // We didn't get to do a GC and we didn't get any memory.
 345         }
 346 
 347         // If this thread is not in a jni critical section, we stall
 348         // the requestor until the critical section has cleared and
 349         // GC allowed. When the critical section clears, a GC is
 350         // initiated by the last thread exiting the critical section; so
 351         // we retry the allocation sequence from the beginning of the loop,
 352         // rather than causing more, now probably unnecessary, GC attempts.
 353         JavaThread* jthr = JavaThread::current();
 354         if (!jthr->in_critical()) {
 355           MutexUnlocker mul(Heap_lock);
 356           // Wait for JNI critical section to be exited
 357           GCLocker::stall_until_clear();
 358           gclocker_stalled_count += 1;
 359           continue;
 360         } else {
 361           if (CheckJNICalls) {
 362             fatal("Possible deadlock due to allocating while"
 363                   " in jni critical section");
 364           }
 365           return NULL;
 366         }
 367       }
 368 
 369       // Read the gc count while the heap lock is held.
 370       gc_count_before = total_collections();
 371     }
 372 
 373     VM_GenCollectForAllocation op(size, is_tlab, gc_count_before);
 374     VMThread::execute(&op);
 375     if (op.prologue_succeeded()) {
 376       result = op.result();
 377       if (op.gc_locked()) {
 378          assert(result == NULL, "must be NULL if gc_locked() is true");
 379          continue;  // Retry and/or stall as necessary.
 380       }
 381 
 382       // Allocation has failed and a collection
 383       // has been done.  If the gc time limit was exceeded the
 384       // this time, return NULL so that an out-of-memory
 385       // will be thrown.  Clear gc_overhead_limit_exceeded
 386       // so that the overhead exceeded does not persist.
 387 
 388       const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
 389       const bool softrefs_clear = soft_ref_policy()->all_soft_refs_clear();
 390 
 391       if (limit_exceeded && softrefs_clear) {
 392         *gc_overhead_limit_was_exceeded = true;
 393         size_policy()->set_gc_overhead_limit_exceeded(false);
 394         if (op.result() != NULL) {
 395           CollectedHeap::fill_with_object(op.result(), size);
 396         }
 397         return NULL;
 398       }
 399       assert(result == NULL || is_in_reserved(result),
 400              "result not in heap");
 401       return result;
 402     }
 403 
 404     // Give a warning if we seem to be looping forever.
 405     if ((QueuedAllocationWarningCount > 0) &&
 406         (try_count % QueuedAllocationWarningCount == 0)) {
 407           log_warning(gc, ergo)("GenCollectedHeap::mem_allocate_work retries %d times,"
 408                                 " size=" SIZE_FORMAT " %s", try_count, size, is_tlab ? "(TLAB)" : "");
 409     }
 410   }
 411 }
 412 
 413 #ifndef PRODUCT
 414 // Override of memory state checking method in CollectedHeap:
 415 // Some collectors (CMS for example) can't have badHeapWordVal written
 416 // in the first two words of an object. (For instance , in the case of
 417 // CMS these words hold state used to synchronize between certain
 418 // (concurrent) GC steps and direct allocating mutators.)
 419 // The skip_header_HeapWords() method below, allows us to skip
 420 // over the requisite number of HeapWord's. Note that (for
 421 // generational collectors) this means that those many words are
 422 // skipped in each object, irrespective of the generation in which
 423 // that object lives. The resultant loss of precision seems to be
 424 // harmless and the pain of avoiding that imprecision appears somewhat
 425 // higher than we are prepared to pay for such rudimentary debugging
 426 // support.
 427 void GenCollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr,
 428                                                          size_t size) {
 429   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
 430     // We are asked to check a size in HeapWords,
 431     // but the memory is mangled in juint words.
 432     juint* start = (juint*) (addr + skip_header_HeapWords());
 433     juint* end   = (juint*) (addr + size);
 434     for (juint* slot = start; slot < end; slot += 1) {
 435       assert(*slot == badHeapWordVal,
 436              "Found non badHeapWordValue in pre-allocation check");
 437     }
 438   }
 439 }
 440 #endif
 441 
 442 HeapWord* GenCollectedHeap::attempt_allocation(size_t size,
 443                                                bool is_tlab,
 444                                                bool first_only) {
 445   HeapWord* res = NULL;
 446 
 447   if (_young_gen->should_allocate(size, is_tlab)) {
 448     res = _young_gen->allocate(size, is_tlab);
 449     if (res != NULL || first_only) {
 450       return res;
 451     }
 452   }
 453 
 454   if (_old_gen->should_allocate(size, is_tlab)) {
 455     res = _old_gen->allocate(size, is_tlab);
 456   }
 457 
 458   return res;
 459 }
 460 
 461 HeapWord* GenCollectedHeap::mem_allocate(size_t size,
 462                                          bool* gc_overhead_limit_was_exceeded) {
 463   return mem_allocate_work(size,
 464                            false /* is_tlab */,
 465                            gc_overhead_limit_was_exceeded);
 466 }
 467 
 468 bool GenCollectedHeap::must_clear_all_soft_refs() {
 469   return _gc_cause == GCCause::_metadata_GC_clear_soft_refs ||
 470          _gc_cause == GCCause::_wb_full_gc;
 471 }
 472 
 473 void GenCollectedHeap::collect_generation(Generation* gen, bool full, size_t size,
 474                                           bool is_tlab, bool run_verification, bool clear_soft_refs,
 475                                           bool restore_marks_for_biased_locking) {
 476   FormatBuffer<> title("Collect gen: %s", gen->short_name());
 477   GCTraceTime(Trace, gc, phases) t1(title);
 478   TraceCollectorStats tcs(gen->counters());
 479   TraceMemoryManagerStats tmms(gen->gc_manager(), gc_cause());
 480 
 481   gen->stat_record()->invocations++;
 482   gen->stat_record()->accumulated_time.start();
 483 
 484   // Must be done anew before each collection because
 485   // a previous collection will do mangling and will
 486   // change top of some spaces.
 487   record_gen_tops_before_GC();
 488 
 489   log_trace(gc)("%s invoke=%d size=" SIZE_FORMAT, heap()->is_young_gen(gen) ? "Young" : "Old", gen->stat_record()->invocations, size * HeapWordSize);
 490 
 491   if (run_verification && VerifyBeforeGC) {
 492     HandleMark hm;  // Discard invalid handles created during verification
 493     Universe::verify("Before GC");
 494   }
 495   COMPILER2_PRESENT(DerivedPointerTable::clear());
 496 
 497   if (restore_marks_for_biased_locking) {
 498     // We perform this mark word preservation work lazily
 499     // because it's only at this point that we know whether we
 500     // absolutely have to do it; we want to avoid doing it for
 501     // scavenge-only collections where it's unnecessary
 502     BiasedLocking::preserve_marks();
 503   }
 504 
 505   // Do collection work
 506   {
 507     // Note on ref discovery: For what appear to be historical reasons,
 508     // GCH enables and disabled (by enqueing) refs discovery.
 509     // In the future this should be moved into the generation's
 510     // collect method so that ref discovery and enqueueing concerns
 511     // are local to a generation. The collect method could return
 512     // an appropriate indication in the case that notification on
 513     // the ref lock was needed. This will make the treatment of
 514     // weak refs more uniform (and indeed remove such concerns
 515     // from GCH). XXX
 516 
 517     HandleMark hm;  // Discard invalid handles created during gc
 518     save_marks();   // save marks for all gens
 519     // We want to discover references, but not process them yet.
 520     // This mode is disabled in process_discovered_references if the
 521     // generation does some collection work, or in
 522     // enqueue_discovered_references if the generation returns
 523     // without doing any work.
 524     ReferenceProcessor* rp = gen->ref_processor();
 525     // If the discovery of ("weak") refs in this generation is
 526     // atomic wrt other collectors in this configuration, we
 527     // are guaranteed to have empty discovered ref lists.
 528     if (rp->discovery_is_atomic()) {
 529       rp->enable_discovery();
 530       rp->setup_policy(clear_soft_refs);
 531     } else {
 532       // collect() below will enable discovery as appropriate
 533     }
 534     gen->collect(full, clear_soft_refs, size, is_tlab);
 535     if (!rp->enqueuing_is_done()) {
 536       rp->disable_discovery();
 537     } else {
 538       rp->set_enqueuing_is_done(false);
 539     }
 540     rp->verify_no_references_recorded();
 541   }
 542 
 543   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 544 
 545   gen->stat_record()->accumulated_time.stop();
 546 
 547   update_gc_stats(gen, full);
 548 
 549   if (run_verification && VerifyAfterGC) {
 550     HandleMark hm;  // Discard invalid handles created during verification
 551     Universe::verify("After GC");
 552   }
 553 }
 554 
 555 void GenCollectedHeap::do_collection(bool           full,
 556                                      bool           clear_all_soft_refs,
 557                                      size_t         size,
 558                                      bool           is_tlab,
 559                                      GenerationType max_generation) {
 560   ResourceMark rm;
 561   DEBUG_ONLY(Thread* my_thread = Thread::current();)
 562 
 563   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 564   assert(my_thread->is_VM_thread() ||
 565          my_thread->is_ConcurrentGC_thread(),
 566          "incorrect thread type capability");
 567   assert(Heap_lock->is_locked(),
 568          "the requesting thread should have the Heap_lock");
 569   guarantee(!is_gc_active(), "collection is not reentrant");
 570 
 571   if (GCLocker::check_active_before_gc()) {
 572     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
 573   }
 574 
 575   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
 576                           soft_ref_policy()->should_clear_all_soft_refs();
 577 
 578   ClearedAllSoftRefs casr(do_clear_all_soft_refs, soft_ref_policy());
 579 
 580   const size_t metadata_prev_used = MetaspaceUtils::used_bytes();
 581 
 582 
 583   FlagSetting fl(_is_gc_active, true);
 584 
 585   bool complete = full && (max_generation == OldGen);
 586   bool old_collects_young = complete && !ScavengeBeforeFullGC;
 587   bool do_young_collection = !old_collects_young && _young_gen->should_collect(full, size, is_tlab);
 588 
 589   size_t young_prev_used = _young_gen->used();
 590   size_t old_prev_used = _old_gen->used();
 591 
 592   bool run_verification = total_collections() >= VerifyGCStartAt;
 593   bool prepared_for_verification = false;
 594   bool do_full_collection = false;
 595 
 596   if (do_young_collection) {
 597     GCIdMark gc_id_mark;
 598     GCTraceCPUTime tcpu;
 599     GCTraceTime(Info, gc) t("Pause Young", NULL, gc_cause(), true);
 600 
 601     print_heap_before_gc();
 602 
 603     if (run_verification && VerifyGCLevel <= 0 && VerifyBeforeGC) {
 604       prepare_for_verify();
 605       prepared_for_verification = true;
 606     }
 607 
 608     gc_prologue(complete);
 609     increment_total_collections(complete);
 610 
 611     collect_generation(_young_gen,
 612                        full,
 613                        size,
 614                        is_tlab,
 615                        run_verification && VerifyGCLevel <= 0,
 616                        do_clear_all_soft_refs,
 617                        false);
 618 
 619     if (size > 0 && (!is_tlab || _young_gen->supports_tlab_allocation()) &&
 620         size * HeapWordSize <= _young_gen->unsafe_max_alloc_nogc()) {
 621       // Allocation request was met by young GC.
 622       size = 0;
 623     }
 624 
 625     // Ask if young collection is enough. If so, do the final steps for young collection,
 626     // and fallthrough to the end.
 627     do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation);
 628     if (!do_full_collection) {
 629       // Adjust generation sizes.
 630       _young_gen->compute_new_size();
 631 
 632       print_heap_change(young_prev_used, old_prev_used);
 633       MetaspaceUtils::print_metaspace_change(metadata_prev_used);
 634 
 635       // Track memory usage and detect low memory after GC finishes
 636       MemoryService::track_memory_usage();
 637 
 638       gc_epilogue(complete);
 639     }
 640 
 641     print_heap_after_gc();
 642 
 643   } else {
 644     // No young collection, ask if we need to perform Full collection.
 645     do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation);
 646   }
 647 
 648   if (do_full_collection) {
 649     GCIdMark gc_id_mark;
 650     GCTraceCPUTime tcpu;
 651     GCTraceTime(Info, gc) t("Pause Full", NULL, gc_cause(), true);
 652 
 653     print_heap_before_gc();
 654 
 655     if (!prepared_for_verification && run_verification &&
 656         VerifyGCLevel <= 1 && VerifyBeforeGC) {
 657       prepare_for_verify();
 658     }
 659 
 660     if (!do_young_collection) {
 661       gc_prologue(complete);
 662       increment_total_collections(complete);
 663     }
 664 
 665     // Accounting quirk: total full collections would be incremented when "complete"
 666     // is set, by calling increment_total_collections above. However, we also need to
 667     // account Full collections that had "complete" unset.
 668     if (!complete) {
 669       increment_total_full_collections();
 670     }
 671 
 672     collect_generation(_old_gen,
 673                        full,
 674                        size,
 675                        is_tlab,
 676                        run_verification && VerifyGCLevel <= 1,
 677                        do_clear_all_soft_refs,
 678                        true);
 679 
 680     // Adjust generation sizes.
 681     _old_gen->compute_new_size();
 682     _young_gen->compute_new_size();
 683 
 684     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
 685     ClassLoaderDataGraph::purge();
 686     MetaspaceUtils::verify_metrics();
 687     // Resize the metaspace capacity after full collections
 688     MetaspaceGC::compute_new_size();
 689     update_full_collections_completed();
 690 
 691     print_heap_change(young_prev_used, old_prev_used);
 692     MetaspaceUtils::print_metaspace_change(metadata_prev_used);
 693 
 694     // Track memory usage and detect low memory after GC finishes
 695     MemoryService::track_memory_usage();
 696 
 697     // Need to tell the epilogue code we are done with Full GC, regardless what was
 698     // the initial value for "complete" flag.
 699     gc_epilogue(true);
 700 
 701     BiasedLocking::restore_marks();
 702 
 703     print_heap_after_gc();
 704   }
 705 
 706 #ifdef TRACESPINNING
 707   ParallelTaskTerminator::print_termination_counts();
 708 #endif
 709 }
 710 
 711 bool GenCollectedHeap::should_do_full_collection(size_t size, bool full, bool is_tlab,
 712                                                  GenCollectedHeap::GenerationType max_gen) const {
 713   return max_gen == OldGen && _old_gen->should_collect(full, size, is_tlab);
 714 }
 715 
 716 void GenCollectedHeap::register_nmethod(nmethod* nm) {
 717   ScavengableNMethods::register_nmethod(nm);
 718 }
 719 
 720 void GenCollectedHeap::unregister_nmethod(nmethod* nm) {
 721   ScavengableNMethods::unregister_nmethod(nm);
 722 }
 723 
 724 void GenCollectedHeap::verify_nmethod(nmethod* nm) {
 725   ScavengableNMethods::verify_nmethod(nm);
 726 }
 727 
 728 void GenCollectedHeap::flush_nmethod(nmethod* nm) {
 729   // Do nothing.
 730 }
 731 
 732 void GenCollectedHeap::prune_scavengable_nmethods() {
 733   ScavengableNMethods::prune_nmethods();
 734 }
 735 
 736 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {
 737   GCCauseSetter x(this, GCCause::_allocation_failure);
 738   HeapWord* result = NULL;
 739 
 740   assert(size != 0, "Precondition violated");
 741   if (GCLocker::is_active_and_needs_gc()) {
 742     // GC locker is active; instead of a collection we will attempt
 743     // to expand the heap, if there's room for expansion.
 744     if (!is_maximal_no_gc()) {
 745       result = expand_heap_and_allocate(size, is_tlab);
 746     }
 747     return result;   // Could be null if we are out of space.
 748   } else if (!incremental_collection_will_fail(false /* don't consult_young */)) {
 749     // Do an incremental collection.
 750     do_collection(false,                     // full
 751                   false,                     // clear_all_soft_refs
 752                   size,                      // size
 753                   is_tlab,                   // is_tlab
 754                   GenCollectedHeap::OldGen); // max_generation
 755   } else {
 756     log_trace(gc)(" :: Trying full because partial may fail :: ");
 757     // Try a full collection; see delta for bug id 6266275
 758     // for the original code and why this has been simplified
 759     // with from-space allocation criteria modified and
 760     // such allocation moved out of the safepoint path.
 761     do_collection(true,                      // full
 762                   false,                     // clear_all_soft_refs
 763                   size,                      // size
 764                   is_tlab,                   // is_tlab
 765                   GenCollectedHeap::OldGen); // max_generation
 766   }
 767 
 768   result = attempt_allocation(size, is_tlab, false /*first_only*/);
 769 
 770   if (result != NULL) {
 771     assert(is_in_reserved(result), "result not in heap");
 772     return result;
 773   }
 774 
 775   // OK, collection failed, try expansion.
 776   result = expand_heap_and_allocate(size, is_tlab);
 777   if (result != NULL) {
 778     return result;
 779   }
 780 
 781   // If we reach this point, we're really out of memory. Try every trick
 782   // we can to reclaim memory. Force collection of soft references. Force
 783   // a complete compaction of the heap. Any additional methods for finding
 784   // free memory should be here, especially if they are expensive. If this
 785   // attempt fails, an OOM exception will be thrown.
 786   {
 787     UIntFlagSetting flag_change(MarkSweepAlwaysCompactCount, 1); // Make sure the heap is fully compacted
 788 
 789     do_collection(true,                      // full
 790                   true,                      // clear_all_soft_refs
 791                   size,                      // size
 792                   is_tlab,                   // is_tlab
 793                   GenCollectedHeap::OldGen); // max_generation
 794   }
 795 
 796   result = attempt_allocation(size, is_tlab, false /* first_only */);
 797   if (result != NULL) {
 798     assert(is_in_reserved(result), "result not in heap");
 799     return result;
 800   }
 801 
 802   assert(!soft_ref_policy()->should_clear_all_soft_refs(),
 803     "Flag should have been handled and cleared prior to this point");
 804 
 805   // What else?  We might try synchronous finalization later.  If the total
 806   // space available is large enough for the allocation, then a more
 807   // complete compaction phase than we've tried so far might be
 808   // appropriate.
 809   return NULL;
 810 }
 811 
 812 #ifdef ASSERT
 813 class AssertNonScavengableClosure: public OopClosure {
 814 public:
 815   virtual void do_oop(oop* p) {
 816     assert(!GenCollectedHeap::heap()->is_in_partial_collection(*p),
 817       "Referent should not be scavengable.");  }
 818   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
 819 };
 820 static AssertNonScavengableClosure assert_is_non_scavengable_closure;
 821 #endif
 822 
 823 void GenCollectedHeap::process_roots(StrongRootsScope* scope,
 824                                      ScanningOption so,
 825                                      OopClosure* strong_roots,
 826                                      CLDClosure* strong_cld_closure,
 827                                      CLDClosure* weak_cld_closure,
 828                                      CodeBlobToOopClosure* code_roots) {
 829   // General roots.
 830   assert(code_roots != NULL, "code root closure should always be set");
 831   // _n_termination for _process_strong_tasks should be set up stream
 832   // in a method not running in a GC worker.  Otherwise the GC worker
 833   // could be trying to change the termination condition while the task
 834   // is executing in another GC worker.
 835 
 836   if (_process_strong_tasks->try_claim_task(GCH_PS_ClassLoaderDataGraph_oops_do)) {
 837     ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure);
 838   }
 839 
 840   // Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway
 841   CodeBlobToOopClosure* roots_from_code_p = (so & SO_AllCodeCache) ? NULL : code_roots;
 842 
 843   bool is_par = scope->n_threads() > 1;
 844   Threads::possibly_parallel_oops_do(is_par, strong_roots, roots_from_code_p);
 845 
 846   if (_process_strong_tasks->try_claim_task(GCH_PS_Universe_oops_do)) {
 847     Universe::oops_do(strong_roots);
 848   }
 849   // Global (strong) JNI handles
 850   if (_process_strong_tasks->try_claim_task(GCH_PS_JNIHandles_oops_do)) {
 851     JNIHandles::oops_do(strong_roots);
 852   }
 853 
 854   if (_process_strong_tasks->try_claim_task(GCH_PS_ObjectSynchronizer_oops_do)) {
 855     ObjectSynchronizer::oops_do(strong_roots);
 856   }
 857   if (_process_strong_tasks->try_claim_task(GCH_PS_Management_oops_do)) {
 858     Management::oops_do(strong_roots);
 859   }
 860   if (_process_strong_tasks->try_claim_task(GCH_PS_jvmti_oops_do)) {
 861     JvmtiExport::oops_do(strong_roots);
 862   }
 863 #if INCLUDE_AOT
 864   if (UseAOT && _process_strong_tasks->try_claim_task(GCH_PS_aot_oops_do)) {
 865     AOTLoader::oops_do(strong_roots);
 866   }
 867 #endif
 868 #if INCLUDE_JVMCI
 869   if (EnableJVMCI && _process_strong_tasks->try_claim_task(GCH_PS_jvmci_oops_do)) {
 870     JVMCI::oops_do(strong_roots);
 871   }
 872 #endif
 873   if (_process_strong_tasks->try_claim_task(GCH_PS_SystemDictionary_oops_do)) {
 874     SystemDictionary::oops_do(strong_roots);
 875   }
 876 
 877   if (_process_strong_tasks->try_claim_task(GCH_PS_CodeCache_oops_do)) {
 878     if (so & SO_ScavengeCodeCache) {
 879       assert(code_roots != NULL, "must supply closure for code cache");
 880 
 881       // We only visit parts of the CodeCache when scavenging.
 882       ScavengableNMethods::nmethods_do(code_roots);
 883     }
 884     if (so & SO_AllCodeCache) {
 885       assert(code_roots != NULL, "must supply closure for code cache");
 886 
 887       // CMSCollector uses this to do intermediate-strength collections.
 888       // We scan the entire code cache, since CodeCache::do_unloading is not called.
 889       CodeCache::blobs_do(code_roots);
 890     }
 891     // Verify that the code cache contents are not subject to
 892     // movement by a scavenging collection.
 893     DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, !CodeBlobToOopClosure::FixRelocations));
 894     DEBUG_ONLY(ScavengableNMethods::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable));
 895   }
 896 }
 897 
 898 void GenCollectedHeap::young_process_roots(StrongRootsScope* scope,
 899                                            OopsInGenClosure* root_closure,
 900                                            OopsInGenClosure* old_gen_closure,
 901                                            CLDClosure* cld_closure) {
 902   MarkingCodeBlobClosure mark_code_closure(root_closure, CodeBlobToOopClosure::FixRelocations);
 903 
 904   process_roots(scope, SO_ScavengeCodeCache, root_closure,
 905                 cld_closure, cld_closure, &mark_code_closure);
 906 
 907   if (_process_strong_tasks->try_claim_task(GCH_PS_younger_gens)) {
 908     root_closure->reset_generation();
 909   }
 910 
 911   // When collection is parallel, all threads get to cooperate to do
 912   // old generation scanning.
 913   old_gen_closure->set_generation(_old_gen);
 914   rem_set()->younger_refs_iterate(_old_gen, old_gen_closure, scope->n_threads());
 915   old_gen_closure->reset_generation();
 916 
 917   _process_strong_tasks->all_tasks_completed(scope->n_threads());
 918 }
 919 
 920 void GenCollectedHeap::full_process_roots(StrongRootsScope* scope,
 921                                           bool is_adjust_phase,
 922                                           ScanningOption so,
 923                                           bool only_strong_roots,
 924                                           OopsInGenClosure* root_closure,
 925                                           CLDClosure* cld_closure) {
 926   MarkingCodeBlobClosure mark_code_closure(root_closure, is_adjust_phase);
 927   CLDClosure* weak_cld_closure = only_strong_roots ? NULL : cld_closure;
 928 
 929   process_roots(scope, so, root_closure, cld_closure, weak_cld_closure, &mark_code_closure);
 930   _process_strong_tasks->all_tasks_completed(scope->n_threads());
 931 }
 932 
 933 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) {
 934   WeakProcessor::oops_do(root_closure);
 935   _young_gen->ref_processor()->weak_oops_do(root_closure);
 936   _old_gen->ref_processor()->weak_oops_do(root_closure);
 937 }
 938 
 939 bool GenCollectedHeap::no_allocs_since_save_marks() {
 940   return _young_gen->no_allocs_since_save_marks() &&
 941          _old_gen->no_allocs_since_save_marks();
 942 }
 943 
 944 bool GenCollectedHeap::supports_inline_contig_alloc() const {
 945   return _young_gen->supports_inline_contig_alloc();
 946 }
 947 
 948 HeapWord* volatile* GenCollectedHeap::top_addr() const {
 949   return _young_gen->top_addr();
 950 }
 951 
 952 HeapWord** GenCollectedHeap::end_addr() const {
 953   return _young_gen->end_addr();
 954 }
 955 
 956 // public collection interfaces
 957 
 958 void GenCollectedHeap::collect(GCCause::Cause cause) {
 959   if (cause == GCCause::_wb_young_gc) {
 960     // Young collection for the WhiteBox API.
 961     collect(cause, YoungGen);
 962   } else {
 963 #ifdef ASSERT
 964   if (cause == GCCause::_scavenge_alot) {
 965     // Young collection only.
 966     collect(cause, YoungGen);
 967   } else {
 968     // Stop-the-world full collection.
 969     collect(cause, OldGen);
 970   }
 971 #else
 972     // Stop-the-world full collection.
 973     collect(cause, OldGen);
 974 #endif
 975   }
 976 }
 977 
 978 void GenCollectedHeap::collect(GCCause::Cause cause, GenerationType max_generation) {
 979   // The caller doesn't have the Heap_lock
 980   assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
 981   MutexLocker ml(Heap_lock);
 982   collect_locked(cause, max_generation);
 983 }
 984 
 985 void GenCollectedHeap::collect_locked(GCCause::Cause cause) {
 986   // The caller has the Heap_lock
 987   assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock");
 988   collect_locked(cause, OldGen);
 989 }
 990 
 991 // this is the private collection interface
 992 // The Heap_lock is expected to be held on entry.
 993 
 994 void GenCollectedHeap::collect_locked(GCCause::Cause cause, GenerationType max_generation) {
 995   // Read the GC count while holding the Heap_lock
 996   unsigned int gc_count_before      = total_collections();
 997   unsigned int full_gc_count_before = total_full_collections();
 998   {
 999     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
1000     VM_GenCollectFull op(gc_count_before, full_gc_count_before,
1001                          cause, max_generation);
1002     VMThread::execute(&op);
1003   }
1004 }
1005 
1006 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1007    do_full_collection(clear_all_soft_refs, OldGen);
1008 }
1009 
1010 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs,
1011                                           GenerationType last_generation) {
1012   GenerationType local_last_generation;
1013   if (!incremental_collection_will_fail(false /* don't consult_young */) &&
1014       gc_cause() == GCCause::_gc_locker) {
1015     local_last_generation = YoungGen;
1016   } else {
1017     local_last_generation = last_generation;
1018   }
1019 
1020   do_collection(true,                   // full
1021                 clear_all_soft_refs,    // clear_all_soft_refs
1022                 0,                      // size
1023                 false,                  // is_tlab
1024                 local_last_generation); // last_generation
1025   // Hack XXX FIX ME !!!
1026   // A scavenge may not have been attempted, or may have
1027   // been attempted and failed, because the old gen was too full
1028   if (local_last_generation == YoungGen && gc_cause() == GCCause::_gc_locker &&
1029       incremental_collection_will_fail(false /* don't consult_young */)) {
1030     log_debug(gc, jni)("GC locker: Trying a full collection because scavenge failed");
1031     // This time allow the old gen to be collected as well
1032     do_collection(true,                // full
1033                   clear_all_soft_refs, // clear_all_soft_refs
1034                   0,                   // size
1035                   false,               // is_tlab
1036                   OldGen);             // last_generation
1037   }
1038 }
1039 
1040 bool GenCollectedHeap::is_in_young(oop p) {
1041   bool result = ((HeapWord*)p) < _old_gen->reserved().start();
1042   assert(result == _young_gen->is_in_reserved(p),
1043          "incorrect test - result=%d, p=" INTPTR_FORMAT, result, p2i((void*)p));
1044   return result;
1045 }
1046 
1047 // Returns "TRUE" iff "p" points into the committed areas of the heap.
1048 bool GenCollectedHeap::is_in(const void* p) const {
1049   return _young_gen->is_in(p) || _old_gen->is_in(p);
1050 }
1051 
1052 #ifdef ASSERT
1053 // Don't implement this by using is_in_young().  This method is used
1054 // in some cases to check that is_in_young() is correct.
1055 bool GenCollectedHeap::is_in_partial_collection(const void* p) {
1056   assert(is_in_reserved(p) || p == NULL,
1057     "Does not work if address is non-null and outside of the heap");
1058   return p < _young_gen->reserved().end() && p != NULL;
1059 }
1060 #endif
1061 
1062 void GenCollectedHeap::oop_iterate(OopIterateClosure* cl) {
1063   _young_gen->oop_iterate(cl);
1064   _old_gen->oop_iterate(cl);
1065 }
1066 
1067 void GenCollectedHeap::object_iterate(ObjectClosure* cl) {
1068   _young_gen->object_iterate(cl);
1069   _old_gen->object_iterate(cl);
1070 }
1071 
1072 void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) {
1073   _young_gen->safe_object_iterate(cl);
1074   _old_gen->safe_object_iterate(cl);
1075 }
1076 
1077 Space* GenCollectedHeap::space_containing(const void* addr) const {
1078   Space* res = _young_gen->space_containing(addr);
1079   if (res != NULL) {
1080     return res;
1081   }
1082   res = _old_gen->space_containing(addr);
1083   assert(res != NULL, "Could not find containing space");
1084   return res;
1085 }
1086 
1087 HeapWord* GenCollectedHeap::block_start(const void* addr) const {
1088   assert(is_in_reserved(addr), "block_start of address outside of heap");
1089   if (_young_gen->is_in_reserved(addr)) {
1090     assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
1091     return _young_gen->block_start(addr);
1092   }
1093 
1094   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
1095   assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
1096   return _old_gen->block_start(addr);
1097 }
1098 
1099 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const {
1100   assert(is_in_reserved(addr), "block_is_obj of address outside of heap");
1101   assert(block_start(addr) == addr, "addr must be a block start");
1102   if (_young_gen->is_in_reserved(addr)) {
1103     return _young_gen->block_is_obj(addr);
1104   }
1105 
1106   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
1107   return _old_gen->block_is_obj(addr);
1108 }
1109 
1110 bool GenCollectedHeap::supports_tlab_allocation() const {
1111   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
1112   return _young_gen->supports_tlab_allocation();
1113 }
1114 
1115 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const {
1116   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
1117   if (_young_gen->supports_tlab_allocation()) {
1118     return _young_gen->tlab_capacity();
1119   }
1120   return 0;
1121 }
1122 
1123 size_t GenCollectedHeap::tlab_used(Thread* thr) const {
1124   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
1125   if (_young_gen->supports_tlab_allocation()) {
1126     return _young_gen->tlab_used();
1127   }
1128   return 0;
1129 }
1130 
1131 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const {
1132   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
1133   if (_young_gen->supports_tlab_allocation()) {
1134     return _young_gen->unsafe_max_tlab_alloc();
1135   }
1136   return 0;
1137 }
1138 
1139 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t min_size,
1140                                               size_t requested_size,
1141                                               size_t* actual_size) {
1142   bool gc_overhead_limit_was_exceeded;
1143   HeapWord* result = mem_allocate_work(requested_size /* size */,
1144                                        true /* is_tlab */,
1145                                        &gc_overhead_limit_was_exceeded);
1146   if (result != NULL) {
1147     *actual_size = requested_size;
1148   }
1149 
1150   return result;
1151 }
1152 
1153 // Requires "*prev_ptr" to be non-NULL.  Deletes and a block of minimal size
1154 // from the list headed by "*prev_ptr".
1155 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) {
1156   bool first = true;
1157   size_t min_size = 0;   // "first" makes this conceptually infinite.
1158   ScratchBlock **smallest_ptr = NULL, *smallest;
1159   ScratchBlock  *cur = *prev_ptr;
1160   while (cur) {
1161     assert(*prev_ptr == cur, "just checking");
1162     if (first || cur->num_words < min_size) {
1163       smallest_ptr = prev_ptr;
1164       smallest     = cur;
1165       min_size     = smallest->num_words;
1166       first        = false;
1167     }
1168     prev_ptr = &cur->next;
1169     cur     =  cur->next;
1170   }
1171   smallest      = *smallest_ptr;
1172   *smallest_ptr = smallest->next;
1173   return smallest;
1174 }
1175 
1176 // Sort the scratch block list headed by res into decreasing size order,
1177 // and set "res" to the result.
1178 static void sort_scratch_list(ScratchBlock*& list) {
1179   ScratchBlock* sorted = NULL;
1180   ScratchBlock* unsorted = list;
1181   while (unsorted) {
1182     ScratchBlock *smallest = removeSmallestScratch(&unsorted);
1183     smallest->next  = sorted;
1184     sorted          = smallest;
1185   }
1186   list = sorted;
1187 }
1188 
1189 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor,
1190                                                size_t max_alloc_words) {
1191   ScratchBlock* res = NULL;
1192   _young_gen->contribute_scratch(res, requestor, max_alloc_words);
1193   _old_gen->contribute_scratch(res, requestor, max_alloc_words);
1194   sort_scratch_list(res);
1195   return res;
1196 }
1197 
1198 void GenCollectedHeap::release_scratch() {
1199   _young_gen->reset_scratch();
1200   _old_gen->reset_scratch();
1201 }
1202 
1203 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure {
1204   void do_generation(Generation* gen) {
1205     gen->prepare_for_verify();
1206   }
1207 };
1208 
1209 void GenCollectedHeap::prepare_for_verify() {
1210   ensure_parsability(false);        // no need to retire TLABs
1211   GenPrepareForVerifyClosure blk;
1212   generation_iterate(&blk, false);
1213 }
1214 
1215 void GenCollectedHeap::generation_iterate(GenClosure* cl,
1216                                           bool old_to_young) {
1217   if (old_to_young) {
1218     cl->do_generation(_old_gen);
1219     cl->do_generation(_young_gen);
1220   } else {
1221     cl->do_generation(_young_gen);
1222     cl->do_generation(_old_gen);
1223   }
1224 }
1225 
1226 bool GenCollectedHeap::is_maximal_no_gc() const {
1227   return _young_gen->is_maximal_no_gc() && _old_gen->is_maximal_no_gc();
1228 }
1229 
1230 void GenCollectedHeap::save_marks() {
1231   _young_gen->save_marks();
1232   _old_gen->save_marks();
1233 }
1234 
1235 GenCollectedHeap* GenCollectedHeap::heap() {
1236   CollectedHeap* heap = Universe::heap();
1237   assert(heap != NULL, "Uninitialized access to GenCollectedHeap::heap()");
1238   assert(heap->kind() == CollectedHeap::Serial ||
1239          heap->kind() == CollectedHeap::CMS, "Invalid name");
1240   return (GenCollectedHeap*) heap;
1241 }
1242 
1243 #if INCLUDE_SERIALGC
1244 void GenCollectedHeap::prepare_for_compaction() {
1245   // Start by compacting into same gen.
1246   CompactPoint cp(_old_gen);
1247   _old_gen->prepare_for_compaction(&cp);
1248   _young_gen->prepare_for_compaction(&cp);
1249 }
1250 #endif // INCLUDE_SERIALGC
1251 
1252 void GenCollectedHeap::verify(VerifyOption option /* ignored */) {
1253   log_debug(gc, verify)("%s", _old_gen->name());
1254   _old_gen->verify();
1255 
1256   log_debug(gc, verify)("%s", _old_gen->name());
1257   _young_gen->verify();
1258 
1259   log_debug(gc, verify)("RemSet");
1260   rem_set()->verify();
1261 }
1262 
1263 void GenCollectedHeap::print_on(outputStream* st) const {
1264   _young_gen->print_on(st);
1265   _old_gen->print_on(st);
1266   MetaspaceUtils::print_on(st);
1267 }
1268 
1269 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const {
1270 }
1271 
1272 void GenCollectedHeap::print_gc_threads_on(outputStream* st) const {
1273 }
1274 
1275 void GenCollectedHeap::print_tracing_info() const {
1276   if (log_is_enabled(Debug, gc, heap, exit)) {
1277     LogStreamHandle(Debug, gc, heap, exit) lsh;
1278     _young_gen->print_summary_info_on(&lsh);
1279     _old_gen->print_summary_info_on(&lsh);
1280   }
1281 }
1282 
1283 void GenCollectedHeap::print_heap_change(size_t young_prev_used, size_t old_prev_used) const {
1284   log_info(gc, heap)("%s: " SIZE_FORMAT "K->" SIZE_FORMAT "K("  SIZE_FORMAT "K)",
1285                      _young_gen->short_name(), young_prev_used / K, _young_gen->used() /K, _young_gen->capacity() /K);
1286   log_info(gc, heap)("%s: " SIZE_FORMAT "K->" SIZE_FORMAT "K("  SIZE_FORMAT "K)",
1287                      _old_gen->short_name(), old_prev_used / K, _old_gen->used() /K, _old_gen->capacity() /K);
1288 }
1289 
1290 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure {
1291  private:
1292   bool _full;
1293  public:
1294   void do_generation(Generation* gen) {
1295     gen->gc_prologue(_full);
1296   }
1297   GenGCPrologueClosure(bool full) : _full(full) {};
1298 };
1299 
1300 void GenCollectedHeap::gc_prologue(bool full) {
1301   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
1302 
1303   // Fill TLAB's and such
1304   ensure_parsability(true);   // retire TLABs
1305 
1306   // Walk generations
1307   GenGCPrologueClosure blk(full);
1308   generation_iterate(&blk, false);  // not old-to-young.
1309 };
1310 
1311 class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure {
1312  private:
1313   bool _full;
1314  public:
1315   void do_generation(Generation* gen) {
1316     gen->gc_epilogue(_full);
1317   }
1318   GenGCEpilogueClosure(bool full) : _full(full) {};
1319 };
1320 
1321 void GenCollectedHeap::gc_epilogue(bool full) {
1322 #if COMPILER2_OR_JVMCI
1323   assert(DerivedPointerTable::is_empty(), "derived pointer present");
1324   size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr()));
1325   guarantee(is_client_compilation_mode_vm() || actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps");
1326 #endif // COMPILER2_OR_JVMCI
1327 
1328   resize_all_tlabs();
1329 
1330   GenGCEpilogueClosure blk(full);
1331   generation_iterate(&blk, false);  // not old-to-young.
1332 
1333   if (!CleanChunkPoolAsync) {
1334     Chunk::clean_chunk_pool();
1335   }
1336 
1337   MetaspaceCounters::update_performance_counters();
1338   CompressedClassSpaceCounters::update_performance_counters();
1339 };
1340 
1341 #ifndef PRODUCT
1342 class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure {
1343  private:
1344  public:
1345   void do_generation(Generation* gen) {
1346     gen->record_spaces_top();
1347   }
1348 };
1349 
1350 void GenCollectedHeap::record_gen_tops_before_GC() {
1351   if (ZapUnusedHeapArea) {
1352     GenGCSaveTopsBeforeGCClosure blk;
1353     generation_iterate(&blk, false);  // not old-to-young.
1354   }
1355 }
1356 #endif  // not PRODUCT
1357 
1358 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure {
1359  public:
1360   void do_generation(Generation* gen) {
1361     gen->ensure_parsability();
1362   }
1363 };
1364 
1365 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) {
1366   CollectedHeap::ensure_parsability(retire_tlabs);
1367   GenEnsureParsabilityClosure ep_cl;
1368   generation_iterate(&ep_cl, false);
1369 }
1370 
1371 oop GenCollectedHeap::handle_failed_promotion(Generation* old_gen,
1372                                               oop obj,
1373                                               size_t obj_size) {
1374   guarantee(old_gen == _old_gen, "We only get here with an old generation");
1375   assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
1376   HeapWord* result = NULL;
1377 
1378   result = old_gen->expand_and_allocate(obj_size, false);
1379 
1380   if (result != NULL) {
1381     Copy::aligned_disjoint_words((HeapWord*)obj, result, obj_size);
1382   }
1383   return oop(result);
1384 }
1385 
1386 class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure {
1387   jlong _time;   // in ms
1388   jlong _now;    // in ms
1389 
1390  public:
1391   GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { }
1392 
1393   jlong time() { return _time; }
1394 
1395   void do_generation(Generation* gen) {
1396     _time = MIN2(_time, gen->time_of_last_gc(_now));
1397   }
1398 };
1399 
1400 jlong GenCollectedHeap::millis_since_last_gc() {
1401   // javaTimeNanos() is guaranteed to be monotonically non-decreasing
1402   // provided the underlying platform provides such a time source
1403   // (and it is bug free). So we still have to guard against getting
1404   // back a time later than 'now'.
1405   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
1406   GenTimeOfLastGCClosure tolgc_cl(now);
1407   // iterate over generations getting the oldest
1408   // time that a generation was collected
1409   generation_iterate(&tolgc_cl, false);
1410 
1411   jlong retVal = now - tolgc_cl.time();
1412   if (retVal < 0) {
1413     log_warning(gc)("millis_since_last_gc() would return : " JLONG_FORMAT
1414        ". returning zero instead.", retVal);
1415     return 0;
1416   }
1417   return retVal;
1418 }