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