1 /*
   2  * Copyright (c) 2017, 2024, 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 "classfile/classLoaderDataGraph.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "compiler/oopMap.hpp"
  32 #include "gc/serial/cardTableRS.hpp"
  33 #include "gc/serial/defNewGeneration.inline.hpp"
  34 #include "gc/serial/serialFullGC.hpp"
  35 #include "gc/serial/serialHeap.inline.hpp"
  36 #include "gc/serial/serialMemoryPools.hpp"
  37 #include "gc/serial/serialVMOperations.hpp"
  38 #include "gc/serial/tenuredGeneration.inline.hpp"
  39 #include "gc/shared/cardTableBarrierSet.hpp"
  40 #include "gc/shared/classUnloadingContext.hpp"
  41 #include "gc/shared/collectedHeap.inline.hpp"
  42 #include "gc/shared/collectorCounters.hpp"
  43 #include "gc/shared/continuationGCSupport.inline.hpp"
  44 #include "gc/shared/gcId.hpp"
  45 #include "gc/shared/gcInitLogger.hpp"
  46 #include "gc/shared/gcLocker.inline.hpp"
  47 #include "gc/shared/gcPolicyCounters.hpp"
  48 #include "gc/shared/gcTrace.hpp"
  49 #include "gc/shared/gcTraceTime.inline.hpp"
  50 #include "gc/shared/gcVMOperations.hpp"
  51 #include "gc/shared/genArguments.hpp"
  52 #include "gc/shared/isGCActiveMark.hpp"
  53 #include "gc/shared/locationPrinter.inline.hpp"
  54 #include "gc/shared/oopStorage.inline.hpp"
  55 #include "gc/shared/oopStorageParState.inline.hpp"
  56 #include "gc/shared/oopStorageSet.inline.hpp"
  57 #include "gc/shared/scavengableNMethods.hpp"
  58 #include "gc/shared/space.hpp"
  59 #include "gc/shared/strongRootsScope.hpp"
  60 #include "gc/shared/suspendibleThreadSet.hpp"
  61 #include "gc/shared/weakProcessor.hpp"
  62 #include "gc/shared/workerThread.hpp"
  63 #include "memory/iterator.hpp"
  64 #include "memory/metaspaceCounters.hpp"
  65 #include "memory/metaspaceUtils.hpp"
  66 #include "memory/resourceArea.hpp"
  67 #include "memory/universe.hpp"
  68 #include "oops/oop.inline.hpp"
  69 #include "runtime/handles.hpp"
  70 #include "runtime/handles.inline.hpp"
  71 #include "runtime/java.hpp"
  72 #include "runtime/mutexLocker.hpp"
  73 #include "runtime/threads.hpp"
  74 #include "runtime/vmThread.hpp"
  75 #include "services/memoryManager.hpp"
  76 #include "services/memoryService.hpp"
  77 #include "utilities/debug.hpp"
  78 #include "utilities/formatBuffer.hpp"
  79 #include "utilities/macros.hpp"
  80 #include "utilities/stack.inline.hpp"
  81 #include "utilities/vmError.hpp"
  82 #if INCLUDE_JVMCI
  83 #include "jvmci/jvmci.hpp"
  84 #endif
  85 
  86 SerialHeap* SerialHeap::heap() {
  87   return named_heap<SerialHeap>(CollectedHeap::Serial);
  88 }
  89 
  90 SerialHeap::SerialHeap() :
  91     CollectedHeap(),
  92     _young_gen(nullptr),
  93     _old_gen(nullptr),
  94     _rem_set(nullptr),
  95     _gc_policy_counters(new GCPolicyCounters("Copy:MSC", 2, 2)),
  96     _incremental_collection_failed(false),
  97     _young_manager(nullptr),
  98     _old_manager(nullptr),
  99     _eden_pool(nullptr),
 100     _survivor_pool(nullptr),
 101     _old_pool(nullptr) {
 102   _young_manager = new GCMemoryManager("Copy");
 103   _old_manager = new GCMemoryManager("MarkSweepCompact");
 104 }
 105 
 106 void SerialHeap::initialize_serviceability() {
 107   DefNewGeneration* young = young_gen();
 108 
 109   // Add a memory pool for each space and young gen doesn't
 110   // support low memory detection as it is expected to get filled up.
 111   _eden_pool = new ContiguousSpacePool(young->eden(),
 112                                        "Eden Space",
 113                                        young->max_eden_size(),
 114                                        false /* support_usage_threshold */);
 115   _survivor_pool = new SurvivorContiguousSpacePool(young,
 116                                                    "Survivor Space",
 117                                                    young->max_survivor_size(),
 118                                                    false /* support_usage_threshold */);
 119   TenuredGeneration* old = old_gen();
 120   _old_pool = new TenuredGenerationPool(old, "Tenured Gen", true);
 121 
 122   _young_manager->add_pool(_eden_pool);
 123   _young_manager->add_pool(_survivor_pool);
 124   young->set_gc_manager(_young_manager);
 125 
 126   _old_manager->add_pool(_eden_pool);
 127   _old_manager->add_pool(_survivor_pool);
 128   _old_manager->add_pool(_old_pool);
 129   old->set_gc_manager(_old_manager);
 130 }
 131 
 132 GrowableArray<GCMemoryManager*> SerialHeap::memory_managers() {
 133   GrowableArray<GCMemoryManager*> memory_managers(2);
 134   memory_managers.append(_young_manager);
 135   memory_managers.append(_old_manager);
 136   return memory_managers;
 137 }
 138 
 139 GrowableArray<MemoryPool*> SerialHeap::memory_pools() {
 140   GrowableArray<MemoryPool*> memory_pools(3);
 141   memory_pools.append(_eden_pool);
 142   memory_pools.append(_survivor_pool);
 143   memory_pools.append(_old_pool);
 144   return memory_pools;
 145 }
 146 
 147 void SerialHeap::safepoint_synchronize_begin() {
 148   if (UseStringDeduplication) {
 149     SuspendibleThreadSet::synchronize();
 150   }
 151 }
 152 
 153 void SerialHeap::safepoint_synchronize_end() {
 154   if (UseStringDeduplication) {
 155     SuspendibleThreadSet::desynchronize();
 156   }
 157 }
 158 
 159 HeapWord* SerialHeap::allocate_loaded_archive_space(size_t word_size) {
 160   MutexLocker ml(Heap_lock);
 161   return old_gen()->allocate(word_size, false /* is_tlab */);
 162 }
 163 
 164 void SerialHeap::complete_loaded_archive_space(MemRegion archive_space) {
 165   assert(old_gen()->used_region().contains(archive_space), "Archive space not contained in old gen");
 166   old_gen()->complete_loaded_archive_space(archive_space);
 167 }
 168 
 169 void SerialHeap::pin_object(JavaThread* thread, oop obj) {
 170   GCLocker::lock_critical(thread);
 171 }
 172 
 173 void SerialHeap::unpin_object(JavaThread* thread, oop obj) {
 174   GCLocker::unlock_critical(thread);
 175 }
 176 
 177 jint SerialHeap::initialize() {
 178   // Allocate space for the heap.
 179 
 180   ReservedHeapSpace heap_rs = allocate(HeapAlignment);
 181 
 182   if (!heap_rs.is_reserved()) {
 183     vm_shutdown_during_initialization(
 184       "Could not reserve enough space for object heap");
 185     return JNI_ENOMEM;
 186   }
 187 
 188   initialize_reserved_region(heap_rs);
 189 
 190   ReservedSpace young_rs = heap_rs.first_part(MaxNewSize);
 191   ReservedSpace old_rs = heap_rs.last_part(MaxNewSize);
 192 
 193   _rem_set = new CardTableRS(heap_rs.region());
 194   _rem_set->initialize(young_rs.base(), old_rs.base());
 195 
 196   CardTableBarrierSet *bs = new CardTableBarrierSet(_rem_set);
 197   bs->initialize();
 198   BarrierSet::set_barrier_set(bs);
 199 
 200   _young_gen = new DefNewGeneration(young_rs, NewSize, MinNewSize, MaxNewSize);
 201   _old_gen = new TenuredGeneration(old_rs, OldSize, MinOldSize, MaxOldSize, rem_set());
 202 
 203   GCInitLogger::print();
 204 
 205   return JNI_OK;
 206 }
 207 
 208 ReservedHeapSpace SerialHeap::allocate(size_t alignment) {
 209   // Now figure out the total size.
 210   const size_t pageSize = UseLargePages ? os::large_page_size() : os::vm_page_size();
 211   assert(alignment % pageSize == 0, "Must be");
 212 
 213   // Check for overflow.
 214   size_t total_reserved = MaxNewSize + MaxOldSize;
 215   if (total_reserved < MaxNewSize) {
 216     vm_exit_during_initialization("The size of the object heap + VM data exceeds "
 217                                   "the maximum representable size");
 218   }
 219   assert(total_reserved % alignment == 0,
 220          "Gen size; total_reserved=" SIZE_FORMAT ", alignment="
 221          SIZE_FORMAT, total_reserved, alignment);
 222 
 223   ReservedHeapSpace heap_rs = Universe::reserve_heap(total_reserved, alignment);
 224   size_t used_page_size = heap_rs.page_size();
 225 
 226   os::trace_page_sizes("Heap",
 227                        MinHeapSize,
 228                        total_reserved,
 229                        heap_rs.base(),
 230                        heap_rs.size(),
 231                        used_page_size);
 232 
 233   return heap_rs;
 234 }
 235 
 236 class GenIsScavengable : public BoolObjectClosure {
 237 public:
 238   bool do_object_b(oop obj) {
 239     return SerialHeap::heap()->is_in_young(obj);
 240   }
 241 };
 242 
 243 static GenIsScavengable _is_scavengable;
 244 
 245 void SerialHeap::post_initialize() {
 246   CollectedHeap::post_initialize();
 247 
 248   DefNewGeneration* def_new_gen = (DefNewGeneration*)_young_gen;
 249 
 250   def_new_gen->ref_processor_init();
 251 
 252   SerialFullGC::initialize();
 253 
 254   ScavengableNMethods::initialize(&_is_scavengable);
 255 }
 256 
 257 PreGenGCValues SerialHeap::get_pre_gc_values() const {
 258   const DefNewGeneration* const def_new_gen = (DefNewGeneration*) young_gen();
 259 
 260   return PreGenGCValues(def_new_gen->used(),
 261                         def_new_gen->capacity(),
 262                         def_new_gen->eden()->used(),
 263                         def_new_gen->eden()->capacity(),
 264                         def_new_gen->from()->used(),
 265                         def_new_gen->from()->capacity(),
 266                         old_gen()->used(),
 267                         old_gen()->capacity());
 268 }
 269 
 270 size_t SerialHeap::capacity() const {
 271   return _young_gen->capacity() + _old_gen->capacity();
 272 }
 273 
 274 size_t SerialHeap::used() const {
 275   return _young_gen->used() + _old_gen->used();
 276 }
 277 
 278 size_t SerialHeap::max_capacity() const {
 279   return _young_gen->max_capacity() + _old_gen->max_capacity();
 280 }
 281 
 282 // Return true if any of the following is true:
 283 // . the allocation won't fit into the current young gen heap
 284 // . gc locker is occupied (jni critical section)
 285 // . heap memory is tight -- the most recent previous collection
 286 //   was a full collection because a partial collection (would
 287 //   have) failed and is likely to fail again
 288 bool SerialHeap::should_try_older_generation_allocation(size_t word_size) const {
 289   size_t young_capacity = _young_gen->capacity_before_gc();
 290   return    (word_size > heap_word_size(young_capacity))
 291          || GCLocker::is_active_and_needs_gc()
 292          || incremental_collection_failed();
 293 }
 294 
 295 HeapWord* SerialHeap::expand_heap_and_allocate(size_t size, bool is_tlab) {
 296   HeapWord* result = nullptr;
 297   if (_old_gen->should_allocate(size, is_tlab)) {
 298     result = _old_gen->expand_and_allocate(size, is_tlab);
 299   }
 300   if (result == nullptr) {
 301     if (_young_gen->should_allocate(size, is_tlab)) {
 302       result = _young_gen->expand_and_allocate(size, is_tlab);
 303     }
 304   }
 305   assert(result == nullptr || is_in_reserved(result), "result not in heap");
 306   return result;
 307 }
 308 
 309 HeapWord* SerialHeap::mem_allocate_work(size_t size,
 310                                         bool is_tlab) {
 311 
 312   HeapWord* result = nullptr;
 313 
 314   // Loop until the allocation is satisfied, or unsatisfied after GC.
 315   for (uint try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) {
 316 
 317     // First allocation attempt is lock-free.
 318     Generation *young = _young_gen;
 319     if (young->should_allocate(size, is_tlab)) {
 320       result = young->par_allocate(size, is_tlab);
 321       if (result != nullptr) {
 322         assert(is_in_reserved(result), "result not in heap");
 323         return result;
 324       }
 325     }
 326     uint gc_count_before;  // Read inside the Heap_lock locked region.
 327     {
 328       MutexLocker ml(Heap_lock);
 329       log_trace(gc, alloc)("SerialHeap::mem_allocate_work: attempting locked slow path allocation");
 330       // Note that only large objects get a shot at being
 331       // allocated in later generations.
 332       bool first_only = !should_try_older_generation_allocation(size);
 333 
 334       result = attempt_allocation(size, is_tlab, first_only);
 335       if (result != nullptr) {
 336         assert(is_in_reserved(result), "result not in heap");
 337         return result;
 338       }
 339 
 340       if (GCLocker::is_active_and_needs_gc()) {
 341         if (is_tlab) {
 342           return nullptr;  // Caller will retry allocating individual object.
 343         }
 344         if (!is_maximal_no_gc()) {
 345           // Try and expand heap to satisfy request.
 346           result = expand_heap_and_allocate(size, is_tlab);
 347           // Result could be null if we are out of space.
 348           if (result != nullptr) {
 349             return result;
 350           }
 351         }
 352 
 353         if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
 354           return nullptr; // We didn't get to do a GC and we didn't get any memory.
 355         }
 356 
 357         // If this thread is not in a jni critical section, we stall
 358         // the requestor until the critical section has cleared and
 359         // GC allowed. When the critical section clears, a GC is
 360         // initiated by the last thread exiting the critical section; so
 361         // we retry the allocation sequence from the beginning of the loop,
 362         // rather than causing more, now probably unnecessary, GC attempts.
 363         JavaThread* jthr = JavaThread::current();
 364         if (!jthr->in_critical()) {
 365           MutexUnlocker mul(Heap_lock);
 366           // Wait for JNI critical section to be exited
 367           GCLocker::stall_until_clear();
 368           gclocker_stalled_count += 1;
 369           continue;
 370         } else {
 371           if (CheckJNICalls) {
 372             fatal("Possible deadlock due to allocating while"
 373                   " in jni critical section");
 374           }
 375           return nullptr;
 376         }
 377       }
 378 
 379       // Read the gc count while the heap lock is held.
 380       gc_count_before = total_collections();
 381     }
 382 
 383     VM_GenCollectForAllocation op(size, is_tlab, gc_count_before);
 384     VMThread::execute(&op);
 385     if (op.prologue_succeeded()) {
 386       result = op.result();
 387       if (op.gc_locked()) {
 388          assert(result == nullptr, "must be null if gc_locked() is true");
 389          continue;  // Retry and/or stall as necessary.
 390       }
 391 
 392       assert(result == nullptr || is_in_reserved(result),
 393              "result not in heap");
 394       return result;
 395     }
 396 
 397     // Give a warning if we seem to be looping forever.
 398     if ((QueuedAllocationWarningCount > 0) &&
 399         (try_count % QueuedAllocationWarningCount == 0)) {
 400           log_warning(gc, ergo)("SerialHeap::mem_allocate_work retries %d times,"
 401                                 " size=" SIZE_FORMAT " %s", try_count, size, is_tlab ? "(TLAB)" : "");
 402     }
 403   }
 404 }
 405 
 406 HeapWord* SerialHeap::attempt_allocation(size_t size,
 407                                          bool is_tlab,
 408                                          bool first_only) {
 409   HeapWord* res = nullptr;
 410 
 411   if (_young_gen->should_allocate(size, is_tlab)) {
 412     res = _young_gen->allocate(size, is_tlab);
 413     if (res != nullptr || first_only) {
 414       return res;
 415     }
 416   }
 417 
 418   if (_old_gen->should_allocate(size, is_tlab)) {
 419     res = _old_gen->allocate(size, is_tlab);
 420   }
 421 
 422   return res;
 423 }
 424 
 425 HeapWord* SerialHeap::mem_allocate(size_t size,
 426                                    bool* gc_overhead_limit_was_exceeded) {
 427   return mem_allocate_work(size,
 428                            false /* is_tlab */);
 429 }
 430 
 431 bool SerialHeap::must_clear_all_soft_refs() {
 432   return _gc_cause == GCCause::_metadata_GC_clear_soft_refs ||
 433          _gc_cause == GCCause::_wb_full_gc;
 434 }
 435 
 436 void SerialHeap::collect_generation(Generation* gen, bool full, size_t size,
 437                                     bool is_tlab, bool run_verification, bool clear_soft_refs) {
 438   FormatBuffer<> title("Collect gen: %s", gen->short_name());
 439   GCTraceTime(Trace, gc, phases) t1(title);
 440   TraceCollectorStats tcs(gen->counters());
 441   TraceMemoryManagerStats tmms(gen->gc_manager(), gc_cause(), heap()->is_young_gen(gen) ? "end of minor GC" : "end of major GC");
 442 
 443   gen->stat_record()->invocations++;
 444   gen->stat_record()->accumulated_time.start();
 445 
 446   // Must be done anew before each collection because
 447   // a previous collection will do mangling and will
 448   // change top of some spaces.
 449   record_gen_tops_before_GC();
 450 
 451   log_trace(gc)("%s invoke=%d size=" SIZE_FORMAT, heap()->is_young_gen(gen) ? "Young" : "Old", gen->stat_record()->invocations, size * HeapWordSize);
 452 
 453   if (run_verification && VerifyBeforeGC) {
 454     Universe::verify("Before GC");
 455   }
 456   COMPILER2_OR_JVMCI_PRESENT(DerivedPointerTable::clear());
 457 
 458   // Do collection work
 459   {
 460     save_marks();   // save marks for all gens
 461 
 462     gen->collect(full, clear_soft_refs, size, is_tlab);
 463   }
 464 
 465   COMPILER2_OR_JVMCI_PRESENT(DerivedPointerTable::update_pointers());
 466 
 467   gen->stat_record()->accumulated_time.stop();
 468 
 469   update_gc_stats(gen, full);
 470 
 471   if (run_verification && VerifyAfterGC) {
 472     Universe::verify("After GC");
 473   }
 474 }
 475 
 476 void SerialHeap::do_collection(bool full,
 477                                bool clear_all_soft_refs,
 478                                size_t size,
 479                                bool is_tlab,
 480                                GenerationType max_generation) {
 481   ResourceMark rm;
 482   DEBUG_ONLY(Thread* my_thread = Thread::current();)
 483 
 484   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 485   assert(my_thread->is_VM_thread(), "only VM thread");
 486   assert(Heap_lock->is_locked(),
 487          "the requesting thread should have the Heap_lock");
 488   guarantee(!is_gc_active(), "collection is not reentrant");
 489 
 490   if (GCLocker::check_active_before_gc()) {
 491     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
 492   }
 493 
 494   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
 495                           soft_ref_policy()->should_clear_all_soft_refs();
 496 
 497   ClearedAllSoftRefs casr(do_clear_all_soft_refs, soft_ref_policy());
 498 
 499   IsGCActiveMark active_gc_mark;
 500 
 501   bool complete = full && (max_generation == OldGen);
 502   bool old_collects_young = complete && !ScavengeBeforeFullGC;
 503   bool do_young_collection = !old_collects_young && _young_gen->should_collect(full, size, is_tlab);
 504 
 505   const PreGenGCValues pre_gc_values = get_pre_gc_values();
 506 
 507   bool run_verification = total_collections() >= VerifyGCStartAt;
 508   bool prepared_for_verification = false;
 509   bool do_full_collection = false;
 510 
 511   if (do_young_collection) {
 512     GCIdMark gc_id_mark;
 513     GCTraceCPUTime tcpu(((DefNewGeneration*)_young_gen)->gc_tracer());
 514     GCTraceTime(Info, gc) t("Pause Young", nullptr, gc_cause(), true);
 515 
 516     print_heap_before_gc();
 517 
 518     if (run_verification && VerifyBeforeGC) {
 519       prepare_for_verify();
 520       prepared_for_verification = true;
 521     }
 522 
 523     gc_prologue(complete);
 524     increment_total_collections(complete);
 525 
 526     collect_generation(_young_gen,
 527                        full,
 528                        size,
 529                        is_tlab,
 530                        run_verification,
 531                        do_clear_all_soft_refs);
 532 
 533     if (size > 0 && (!is_tlab || _young_gen->supports_tlab_allocation()) &&
 534         size * HeapWordSize <= _young_gen->unsafe_max_alloc_nogc()) {
 535       // Allocation request was met by young GC.
 536       size = 0;
 537     }
 538 
 539     // Ask if young collection is enough. If so, do the final steps for young collection,
 540     // and fallthrough to the end.
 541     do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation);
 542     if (!do_full_collection) {
 543       // Adjust generation sizes.
 544       _young_gen->compute_new_size();
 545 
 546       print_heap_change(pre_gc_values);
 547 
 548       // Track memory usage and detect low memory after GC finishes
 549       MemoryService::track_memory_usage();
 550 
 551       gc_epilogue(complete);
 552     }
 553 
 554     print_heap_after_gc();
 555 
 556   } else {
 557     // No young collection, ask if we need to perform Full collection.
 558     do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation);
 559   }
 560 
 561   if (do_full_collection) {
 562     GCIdMark gc_id_mark;
 563     GCTraceCPUTime tcpu(SerialFullGC::gc_tracer());
 564     GCTraceTime(Info, gc) t("Pause Full", nullptr, gc_cause(), true);
 565 
 566     print_heap_before_gc();
 567 
 568     if (!prepared_for_verification && run_verification && VerifyBeforeGC) {
 569       prepare_for_verify();
 570     }
 571 
 572     if (!do_young_collection) {
 573       gc_prologue(complete);
 574       increment_total_collections(complete);
 575     }
 576 
 577     // Accounting quirk: total full collections would be incremented when "complete"
 578     // is set, by calling increment_total_collections above. However, we also need to
 579     // account Full collections that had "complete" unset.
 580     if (!complete) {
 581       increment_total_full_collections();
 582     }
 583 
 584     CodeCache::on_gc_marking_cycle_start();
 585 
 586     ClassUnloadingContext ctx(1 /* num_nmethod_unlink_workers */,
 587                               false /* unregister_nmethods_during_purge */,
 588                               false /* lock_nmethod_free_separately */);
 589 
 590     collect_generation(_old_gen,
 591                        full,
 592                        size,
 593                        is_tlab,
 594                        run_verification,
 595                        do_clear_all_soft_refs);
 596 
 597     CodeCache::on_gc_marking_cycle_finish();
 598     CodeCache::arm_all_nmethods();
 599 
 600     // Adjust generation sizes.
 601     _old_gen->compute_new_size();
 602     _young_gen->compute_new_size();
 603 
 604     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
 605     ClassLoaderDataGraph::purge(/*at_safepoint*/true);
 606     DEBUG_ONLY(MetaspaceUtils::verify();)
 607 
 608     // Need to clear claim bits for the next mark.
 609     ClassLoaderDataGraph::clear_claimed_marks();
 610 
 611     // Resize the metaspace capacity after full collections
 612     MetaspaceGC::compute_new_size();
 613 
 614     print_heap_change(pre_gc_values);
 615 
 616     // Track memory usage and detect low memory after GC finishes
 617     MemoryService::track_memory_usage();
 618 
 619     // Need to tell the epilogue code we are done with Full GC, regardless what was
 620     // the initial value for "complete" flag.
 621     gc_epilogue(true);
 622 
 623     print_heap_after_gc();
 624   }
 625 }
 626 
 627 bool SerialHeap::should_do_full_collection(size_t size, bool full, bool is_tlab,
 628                                            SerialHeap::GenerationType max_gen) const {
 629   return max_gen == OldGen && _old_gen->should_collect(full, size, is_tlab);
 630 }
 631 
 632 void SerialHeap::register_nmethod(nmethod* nm) {
 633   ScavengableNMethods::register_nmethod(nm);
 634 }
 635 
 636 void SerialHeap::unregister_nmethod(nmethod* nm) {
 637   ScavengableNMethods::unregister_nmethod(nm);
 638 }
 639 
 640 void SerialHeap::verify_nmethod(nmethod* nm) {
 641   ScavengableNMethods::verify_nmethod(nm);
 642 }
 643 
 644 void SerialHeap::prune_scavengable_nmethods() {
 645   ScavengableNMethods::prune_nmethods_not_into_young();
 646 }
 647 
 648 void SerialHeap::prune_unlinked_nmethods() {
 649   ScavengableNMethods::prune_unlinked_nmethods();
 650 }
 651 
 652 HeapWord* SerialHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {
 653   GCCauseSetter x(this, GCCause::_allocation_failure);
 654   HeapWord* result = nullptr;
 655 
 656   assert(size != 0, "Precondition violated");
 657   if (GCLocker::is_active_and_needs_gc()) {
 658     // GC locker is active; instead of a collection we will attempt
 659     // to expand the heap, if there's room for expansion.
 660     if (!is_maximal_no_gc()) {
 661       result = expand_heap_and_allocate(size, is_tlab);
 662     }
 663     return result;   // Could be null if we are out of space.
 664   } else if (!incremental_collection_will_fail(false /* don't consult_young */)) {
 665     // Do an incremental collection.
 666     do_collection(false,                     // full
 667                   false,                     // clear_all_soft_refs
 668                   size,                      // size
 669                   is_tlab,                   // is_tlab
 670                   SerialHeap::OldGen); // max_generation
 671   } else {
 672     log_trace(gc)(" :: Trying full because partial may fail :: ");
 673     // Try a full collection; see delta for bug id 6266275
 674     // for the original code and why this has been simplified
 675     // with from-space allocation criteria modified and
 676     // such allocation moved out of the safepoint path.
 677     do_collection(true,                      // full
 678                   false,                     // clear_all_soft_refs
 679                   size,                      // size
 680                   is_tlab,                   // is_tlab
 681                   SerialHeap::OldGen); // max_generation
 682   }
 683 
 684   result = attempt_allocation(size, is_tlab, false /*first_only*/);
 685 
 686   if (result != nullptr) {
 687     assert(is_in_reserved(result), "result not in heap");
 688     return result;
 689   }
 690 
 691   // OK, collection failed, try expansion.
 692   result = expand_heap_and_allocate(size, is_tlab);
 693   if (result != nullptr) {
 694     return result;
 695   }
 696 
 697   // If we reach this point, we're really out of memory. Try every trick
 698   // we can to reclaim memory. Force collection of soft references. Force
 699   // a complete compaction of the heap. Any additional methods for finding
 700   // free memory should be here, especially if they are expensive. If this
 701   // attempt fails, an OOM exception will be thrown.
 702   {
 703     UIntFlagSetting flag_change(MarkSweepAlwaysCompactCount, 1); // Make sure the heap is fully compacted
 704 
 705     do_collection(true,                      // full
 706                   true,                      // clear_all_soft_refs
 707                   size,                      // size
 708                   is_tlab,                   // is_tlab
 709                   SerialHeap::OldGen); // max_generation
 710   }
 711 
 712   result = attempt_allocation(size, is_tlab, false /* first_only */);
 713   if (result != nullptr) {
 714     assert(is_in_reserved(result), "result not in heap");
 715     return result;
 716   }
 717 
 718   assert(!soft_ref_policy()->should_clear_all_soft_refs(),
 719     "Flag should have been handled and cleared prior to this point");
 720 
 721   // What else?  We might try synchronous finalization later.  If the total
 722   // space available is large enough for the allocation, then a more
 723   // complete compaction phase than we've tried so far might be
 724   // appropriate.
 725   return nullptr;
 726 }
 727 
 728 void SerialHeap::process_roots(ScanningOption so,
 729                                OopClosure* strong_roots,
 730                                CLDClosure* strong_cld_closure,
 731                                CLDClosure* weak_cld_closure,
 732                                NMethodToOopClosure* code_roots) {
 733   // General roots.
 734   assert(code_roots != nullptr, "code root closure should always be set");
 735 
 736   ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure);
 737 
 738   // Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway
 739   NMethodToOopClosure* roots_from_code_p = (so & SO_AllCodeCache) ? nullptr : code_roots;
 740 
 741   Threads::oops_do(strong_roots, roots_from_code_p);
 742 
 743   OopStorageSet::strong_oops_do(strong_roots);
 744 
 745   if (so & SO_ScavengeCodeCache) {
 746     assert(code_roots != nullptr, "must supply closure for code cache");
 747 
 748     // We only visit parts of the CodeCache when scavenging.
 749     ScavengableNMethods::nmethods_do(code_roots);
 750   }
 751   if (so & SO_AllCodeCache) {
 752     assert(code_roots != nullptr, "must supply closure for code cache");
 753 
 754     // CMSCollector uses this to do intermediate-strength collections.
 755     // We scan the entire code cache, since CodeCache::do_unloading is not called.
 756     CodeCache::nmethods_do(code_roots);
 757   }
 758 }
 759 
 760 bool SerialHeap::no_allocs_since_save_marks() {
 761   return _young_gen->no_allocs_since_save_marks() &&
 762          _old_gen->no_allocs_since_save_marks();
 763 }
 764 
 765 void SerialHeap::scan_evacuated_objs(YoungGenScanClosure* young_cl,
 766                                      OldGenScanClosure* old_cl) {
 767   do {
 768     young_gen()->oop_since_save_marks_iterate(young_cl);
 769     old_gen()->oop_since_save_marks_iterate(old_cl);
 770   } while (!no_allocs_since_save_marks());
 771   guarantee(young_gen()->promo_failure_scan_is_complete(), "Failed to finish scan");
 772 }
 773 
 774 // public collection interfaces
 775 void SerialHeap::collect(GCCause::Cause cause) {
 776   // The caller doesn't have the Heap_lock
 777   assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
 778 
 779   unsigned int gc_count_before;
 780   unsigned int full_gc_count_before;
 781 
 782   {
 783     MutexLocker ml(Heap_lock);
 784     // Read the GC count while holding the Heap_lock
 785     gc_count_before      = total_collections();
 786     full_gc_count_before = total_full_collections();
 787   }
 788 
 789   if (GCLocker::should_discard(cause, gc_count_before)) {
 790     return;
 791   }
 792 
 793   bool should_run_young_gc =  (cause == GCCause::_wb_young_gc)
 794                            || (cause == GCCause::_gc_locker)
 795                 DEBUG_ONLY(|| (cause == GCCause::_scavenge_alot));
 796 
 797   const GenerationType max_generation = should_run_young_gc
 798                                       ? YoungGen
 799                                       : OldGen;
 800 
 801   while (true) {
 802     VM_GenCollectFull op(gc_count_before, full_gc_count_before,
 803                          cause, max_generation);
 804     VMThread::execute(&op);
 805 
 806     if (!GCCause::is_explicit_full_gc(cause)) {
 807       return;
 808     }
 809 
 810     {
 811       MutexLocker ml(Heap_lock);
 812       // Read the GC count while holding the Heap_lock
 813       if (full_gc_count_before != total_full_collections()) {
 814         return;
 815       }
 816     }
 817 
 818     if (GCLocker::is_active_and_needs_gc()) {
 819       // If GCLocker is active, wait until clear before retrying.
 820       GCLocker::stall_until_clear();
 821     }
 822   }
 823 }
 824 
 825 void SerialHeap::do_full_collection(bool clear_all_soft_refs) {
 826    do_full_collection(clear_all_soft_refs, OldGen);
 827 }
 828 
 829 void SerialHeap::do_full_collection(bool clear_all_soft_refs,
 830                                     GenerationType last_generation) {
 831   do_collection(true,                   // full
 832                 clear_all_soft_refs,    // clear_all_soft_refs
 833                 0,                      // size
 834                 false,                  // is_tlab
 835                 last_generation);       // last_generation
 836   // Hack XXX FIX ME !!!
 837   // A scavenge may not have been attempted, or may have
 838   // been attempted and failed, because the old gen was too full
 839   if (gc_cause() == GCCause::_gc_locker && incremental_collection_failed()) {
 840     log_debug(gc, jni)("GC locker: Trying a full collection because scavenge failed");
 841     // This time allow the old gen to be collected as well
 842     do_collection(true,                // full
 843                   clear_all_soft_refs, // clear_all_soft_refs
 844                   0,                   // size
 845                   false,               // is_tlab
 846                   OldGen);             // last_generation
 847   }
 848 }
 849 
 850 bool SerialHeap::is_in_young(const void* p) const {
 851   bool result = p < _old_gen->reserved().start();
 852   assert(result == _young_gen->is_in_reserved(p),
 853          "incorrect test - result=%d, p=" PTR_FORMAT, result, p2i(p));
 854   return result;
 855 }
 856 
 857 bool SerialHeap::requires_barriers(stackChunkOop obj) const {
 858   return !is_in_young(obj);
 859 }
 860 
 861 // Returns "TRUE" iff "p" points into the committed areas of the heap.
 862 bool SerialHeap::is_in(const void* p) const {
 863   return _young_gen->is_in(p) || _old_gen->is_in(p);
 864 }
 865 
 866 void SerialHeap::object_iterate(ObjectClosure* cl) {
 867   _young_gen->object_iterate(cl);
 868   _old_gen->object_iterate(cl);
 869 }
 870 
 871 HeapWord* SerialHeap::block_start(const void* addr) const {
 872   assert(is_in_reserved(addr), "block_start of address outside of heap");
 873   if (_young_gen->is_in_reserved(addr)) {
 874     assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
 875     return _young_gen->block_start(addr);
 876   }
 877 
 878   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
 879   assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
 880   return _old_gen->block_start(addr);
 881 }
 882 
 883 bool SerialHeap::block_is_obj(const HeapWord* addr) const {
 884   assert(is_in_reserved(addr), "block_is_obj of address outside of heap");
 885   assert(block_start(addr) == addr, "addr must be a block start");
 886 
 887   if (_young_gen->is_in_reserved(addr)) {
 888     return _young_gen->eden()->is_in(addr)
 889         || _young_gen->from()->is_in(addr)
 890         || _young_gen->to()  ->is_in(addr);
 891   }
 892 
 893   assert(_old_gen->is_in_reserved(addr), "must be in old-gen");
 894   return addr < _old_gen->space()->top();
 895 }
 896 
 897 size_t SerialHeap::tlab_capacity(Thread* thr) const {
 898   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 899   assert(_young_gen->supports_tlab_allocation(), "Young gen doesn't support TLAB allocation?!");
 900   return _young_gen->tlab_capacity();
 901 }
 902 
 903 size_t SerialHeap::tlab_used(Thread* thr) const {
 904   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 905   assert(_young_gen->supports_tlab_allocation(), "Young gen doesn't support TLAB allocation?!");
 906   return _young_gen->tlab_used();
 907 }
 908 
 909 size_t SerialHeap::unsafe_max_tlab_alloc(Thread* thr) const {
 910   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 911   assert(_young_gen->supports_tlab_allocation(), "Young gen doesn't support TLAB allocation?!");
 912   return _young_gen->unsafe_max_tlab_alloc();
 913 }
 914 
 915 HeapWord* SerialHeap::allocate_new_tlab(size_t min_size,
 916                                         size_t requested_size,
 917                                         size_t* actual_size) {
 918   HeapWord* result = mem_allocate_work(requested_size /* size */,
 919                                        true /* is_tlab */);
 920   if (result != nullptr) {
 921     *actual_size = requested_size;
 922   }
 923 
 924   return result;
 925 }
 926 
 927 void SerialHeap::prepare_for_verify() {
 928   ensure_parsability(false);        // no need to retire TLABs
 929 }
 930 
 931 bool SerialHeap::is_maximal_no_gc() const {
 932   // We don't expand young-gen except at a GC.
 933   return _old_gen->is_maximal_no_gc();
 934 }
 935 
 936 void SerialHeap::save_marks() {
 937   _young_gen->save_marks();
 938   _old_gen->save_marks();
 939 }
 940 
 941 void SerialHeap::verify(VerifyOption option /* ignored */) {
 942   log_debug(gc, verify)("%s", _old_gen->name());
 943   _old_gen->verify();
 944 
 945   log_debug(gc, verify)("%s", _young_gen->name());
 946   _young_gen->verify();
 947 
 948   log_debug(gc, verify)("RemSet");
 949   rem_set()->verify();
 950 }
 951 
 952 void SerialHeap::print_on(outputStream* st) const {
 953   if (_young_gen != nullptr) {
 954     _young_gen->print_on(st);
 955   }
 956   if (_old_gen != nullptr) {
 957     _old_gen->print_on(st);
 958   }
 959   MetaspaceUtils::print_on(st);
 960 }
 961 
 962 void SerialHeap::gc_threads_do(ThreadClosure* tc) const {
 963 }
 964 
 965 bool SerialHeap::print_location(outputStream* st, void* addr) const {
 966   return BlockLocationPrinter<SerialHeap>::print_location(st, addr);
 967 }
 968 
 969 void SerialHeap::print_tracing_info() const {
 970   if (log_is_enabled(Debug, gc, heap, exit)) {
 971     LogStreamHandle(Debug, gc, heap, exit) lsh;
 972     _young_gen->print_summary_info_on(&lsh);
 973     _old_gen->print_summary_info_on(&lsh);
 974   }
 975 }
 976 
 977 void SerialHeap::print_heap_change(const PreGenGCValues& pre_gc_values) const {
 978   const DefNewGeneration* const def_new_gen = (DefNewGeneration*) young_gen();
 979 
 980   log_info(gc, heap)(HEAP_CHANGE_FORMAT" "
 981                      HEAP_CHANGE_FORMAT" "
 982                      HEAP_CHANGE_FORMAT,
 983                      HEAP_CHANGE_FORMAT_ARGS(def_new_gen->short_name(),
 984                                              pre_gc_values.young_gen_used(),
 985                                              pre_gc_values.young_gen_capacity(),
 986                                              def_new_gen->used(),
 987                                              def_new_gen->capacity()),
 988                      HEAP_CHANGE_FORMAT_ARGS("Eden",
 989                                              pre_gc_values.eden_used(),
 990                                              pre_gc_values.eden_capacity(),
 991                                              def_new_gen->eden()->used(),
 992                                              def_new_gen->eden()->capacity()),
 993                      HEAP_CHANGE_FORMAT_ARGS("From",
 994                                              pre_gc_values.from_used(),
 995                                              pre_gc_values.from_capacity(),
 996                                              def_new_gen->from()->used(),
 997                                              def_new_gen->from()->capacity()));
 998   log_info(gc, heap)(HEAP_CHANGE_FORMAT,
 999                      HEAP_CHANGE_FORMAT_ARGS(old_gen()->short_name(),
1000                                              pre_gc_values.old_gen_used(),
1001                                              pre_gc_values.old_gen_capacity(),
1002                                              old_gen()->used(),
1003                                              old_gen()->capacity()));
1004   MetaspaceUtils::print_metaspace_change(pre_gc_values.metaspace_sizes());
1005 }
1006 
1007 void SerialHeap::gc_prologue(bool full) {
1008   // Fill TLAB's and such
1009   ensure_parsability(true);   // retire TLABs
1010 
1011   _old_gen->gc_prologue();
1012 };
1013 
1014 void SerialHeap::gc_epilogue(bool full) {
1015 #if COMPILER2_OR_JVMCI
1016   assert(DerivedPointerTable::is_empty(), "derived pointer present");
1017 #endif // COMPILER2_OR_JVMCI
1018 
1019   resize_all_tlabs();
1020 
1021   _young_gen->gc_epilogue(full);
1022   _old_gen->gc_epilogue();
1023 
1024   MetaspaceCounters::update_performance_counters();
1025 };
1026 
1027 #ifndef PRODUCT
1028 void SerialHeap::record_gen_tops_before_GC() {
1029   if (ZapUnusedHeapArea) {
1030     _young_gen->record_spaces_top();
1031     _old_gen->record_spaces_top();
1032   }
1033 }
1034 #endif  // not PRODUCT