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