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