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