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