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