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