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