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