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