1 /* 2 * Copyright (c) 2000, 2020, 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 "aot/aotLoader.hpp" 27 #include "classfile/classLoaderDataGraph.hpp" 28 #include "classfile/symbolTable.hpp" 29 #include "classfile/stringTable.hpp" 30 #include "classfile/vmSymbols.hpp" 31 #include "code/codeCache.hpp" 32 #include "code/icBuffer.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/space.hpp" 56 #include "gc/shared/strongRootsScope.hpp" 57 #include "gc/shared/weakProcessor.hpp" 58 #include "gc/shared/workgroup.hpp" 59 #include "memory/filemap.hpp" 60 #include "memory/iterator.hpp" 61 #include "memory/metaspaceCounters.hpp" 62 #include "memory/resourceArea.hpp" 63 #include "memory/universe.hpp" 64 #include "oops/oop.inline.hpp" 65 #include "runtime/biasedLocking.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 _process_strong_tasks(new SubTasksDone(GCH_PS_NumElements)), 102 _young_manager(NULL), 103 _old_manager(NULL) { 104 } 105 106 jint GenCollectedHeap::initialize() { 107 // While there are no constraints in the GC code that HeapWordSize 108 // be any particular value, there are multiple other areas in the 109 // system which believe this to be true (e.g. oop->object_size in some 110 // cases incorrectly returns the size in wordSize units rather than 111 // HeapWordSize). 112 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize"); 113 114 // Allocate space for the heap. 115 116 ReservedHeapSpace heap_rs = allocate(HeapAlignment); 117 118 if (!heap_rs.is_reserved()) { 119 vm_shutdown_during_initialization( 120 "Could not reserve enough space for object heap"); 121 return JNI_ENOMEM; 122 } 123 124 initialize_reserved_region(heap_rs); 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, false /* scan_concurrently */); 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 176 os::trace_page_sizes("Heap", 177 MinHeapSize, 178 total_reserved, 179 alignment, 180 heap_rs.base(), 181 heap_rs.size()); 182 183 return heap_rs; 184 } 185 186 class GenIsScavengable : public BoolObjectClosure { 187 public: 188 bool do_object_b(oop obj) { 189 return GenCollectedHeap::heap()->is_in_young(obj); 190 } 191 }; 192 193 static GenIsScavengable _is_scavengable; 194 195 void GenCollectedHeap::post_initialize() { 196 CollectedHeap::post_initialize(); 197 ref_processing_init(); 198 199 DefNewGeneration* def_new_gen = (DefNewGeneration*)_young_gen; 200 201 initialize_size_policy(def_new_gen->eden()->capacity(), 202 _old_gen->capacity(), 203 def_new_gen->from()->capacity()); 204 205 MarkSweep::initialize(); 206 207 ScavengableNMethods::initialize(&_is_scavengable); 208 } 209 210 void GenCollectedHeap::ref_processing_init() { 211 _young_gen->ref_processor_init(); 212 _old_gen->ref_processor_init(); 213 } 214 215 PreGenGCValues GenCollectedHeap::get_pre_gc_values() const { 216 const DefNewGeneration* const def_new_gen = (DefNewGeneration*) young_gen(); 217 218 return PreGenGCValues(def_new_gen->used(), 219 def_new_gen->capacity(), 220 def_new_gen->eden()->used(), 221 def_new_gen->eden()->capacity(), 222 def_new_gen->from()->used(), 223 def_new_gen->from()->capacity(), 224 old_gen()->used(), 225 old_gen()->capacity()); 226 } 227 228 GenerationSpec* GenCollectedHeap::young_gen_spec() const { 229 return _young_gen_spec; 230 } 231 232 GenerationSpec* GenCollectedHeap::old_gen_spec() const { 233 return _old_gen_spec; 234 } 235 236 size_t GenCollectedHeap::capacity() const { 237 return _young_gen->capacity() + _old_gen->capacity(); 238 } 239 240 size_t GenCollectedHeap::used() const { 241 return _young_gen->used() + _old_gen->used(); 242 } 243 244 void GenCollectedHeap::save_used_regions() { 245 _old_gen->save_used_region(); 246 _young_gen->save_used_region(); 247 } 248 249 size_t GenCollectedHeap::max_capacity() const { 250 return _young_gen->max_capacity() + _old_gen->max_capacity(); 251 } 252 253 // Update the _full_collections_completed counter 254 // at the end of a stop-world full GC. 255 unsigned int GenCollectedHeap::update_full_collections_completed() { 256 MonitorLocker ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag); 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 ml.notify_all(); 261 return _full_collections_completed; 262 } 263 264 // Update the _full_collections_completed counter, as appropriate, 265 // at the end of a concurrent GC cycle. Note the conditional update 266 // below to allow this method to be called by a concurrent collector 267 // without synchronizing in any manner with the VM thread (which 268 // may already have initiated a STW full collection "concurrently"). 269 unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) { 270 MonitorLocker ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag); 271 assert((_full_collections_completed <= _total_full_collections) && 272 (count <= _total_full_collections), 273 "Can't complete more collections than were started"); 274 if (count > _full_collections_completed) { 275 _full_collections_completed = count; 276 ml.notify_all(); 277 } 278 return _full_collections_completed; 279 } 280 281 // Return true if any of the following is true: 282 // . the allocation won't fit into the current young gen heap 283 // . gc locker is occupied (jni critical section) 284 // . heap memory is tight -- the most recent previous collection 285 // was a full collection because a partial collection (would 286 // have) failed and is likely to fail again 287 bool GenCollectedHeap::should_try_older_generation_allocation(size_t word_size) const { 288 size_t young_capacity = _young_gen->capacity_before_gc(); 289 return (word_size > heap_word_size(young_capacity)) 290 || GCLocker::is_active_and_needs_gc() 291 || incremental_collection_failed(); 292 } 293 294 HeapWord* GenCollectedHeap::expand_heap_and_allocate(size_t size, bool is_tlab) { 295 HeapWord* result = NULL; 296 if (_old_gen->should_allocate(size, is_tlab)) { 297 result = _old_gen->expand_and_allocate(size, is_tlab); 298 } 299 if (result == NULL) { 300 if (_young_gen->should_allocate(size, is_tlab)) { 301 result = _young_gen->expand_and_allocate(size, is_tlab); 302 } 303 } 304 assert(result == NULL || is_in_reserved(result), "result not in heap"); 305 return result; 306 } 307 308 HeapWord* GenCollectedHeap::mem_allocate_work(size_t size, 309 bool is_tlab, 310 bool* gc_overhead_limit_was_exceeded) { 311 // In general gc_overhead_limit_was_exceeded should be false so 312 // set it so here and reset it to true only if the gc time 313 // limit is being exceeded as checked below. 314 *gc_overhead_limit_was_exceeded = false; 315 316 HeapWord* result = NULL; 317 318 // Loop until the allocation is satisfied, or unsatisfied after GC. 319 for (uint try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) { 320 HandleMark hm; // Discard any handles allocated in each iteration. 321 322 // First allocation attempt is lock-free. 323 Generation *young = _young_gen; 324 assert(young->supports_inline_contig_alloc(), 325 "Otherwise, must do alloc within heap lock"); 326 if (young->should_allocate(size, is_tlab)) { 327 result = young->par_allocate(size, is_tlab); 328 if (result != NULL) { 329 assert(is_in_reserved(result), "result not in heap"); 330 return result; 331 } 332 } 333 uint gc_count_before; // Read inside the Heap_lock locked region. 334 { 335 MutexLocker ml(Heap_lock); 336 log_trace(gc, alloc)("GenCollectedHeap::mem_allocate_work: attempting locked slow path allocation"); 337 // Note that only large objects get a shot at being 338 // allocated in later generations. 339 bool first_only = !should_try_older_generation_allocation(size); 340 341 result = attempt_allocation(size, is_tlab, first_only); 342 if (result != NULL) { 343 assert(is_in_reserved(result), "result not in heap"); 344 return result; 345 } 346 347 if (GCLocker::is_active_and_needs_gc()) { 348 if (is_tlab) { 349 return NULL; // Caller will retry allocating individual object. 350 } 351 if (!is_maximal_no_gc()) { 352 // Try and expand heap to satisfy request. 353 result = expand_heap_and_allocate(size, is_tlab); 354 // Result could be null if we are out of space. 355 if (result != NULL) { 356 return result; 357 } 358 } 359 360 if (gclocker_stalled_count > GCLockerRetryAllocationCount) { 361 return NULL; // We didn't get to do a GC and we didn't get any memory. 362 } 363 364 // If this thread is not in a jni critical section, we stall 365 // the requestor until the critical section has cleared and 366 // GC allowed. When the critical section clears, a GC is 367 // initiated by the last thread exiting the critical section; so 368 // we retry the allocation sequence from the beginning of the loop, 369 // rather than causing more, now probably unnecessary, GC attempts. 370 JavaThread* jthr = JavaThread::current(); 371 if (!jthr->in_critical()) { 372 MutexUnlocker mul(Heap_lock); 373 // Wait for JNI critical section to be exited 374 GCLocker::stall_until_clear(); 375 gclocker_stalled_count += 1; 376 continue; 377 } else { 378 if (CheckJNICalls) { 379 fatal("Possible deadlock due to allocating while" 380 " in jni critical section"); 381 } 382 return NULL; 383 } 384 } 385 386 // Read the gc count while the heap lock is held. 387 gc_count_before = total_collections(); 388 } 389 390 VM_GenCollectForAllocation op(size, is_tlab, gc_count_before); 391 VMThread::execute(&op); 392 if (op.prologue_succeeded()) { 393 result = op.result(); 394 if (op.gc_locked()) { 395 assert(result == NULL, "must be NULL if gc_locked() is true"); 396 continue; // Retry and/or stall as necessary. 397 } 398 399 // Allocation has failed and a collection 400 // has been done. If the gc time limit was exceeded the 401 // this time, return NULL so that an out-of-memory 402 // will be thrown. Clear gc_overhead_limit_exceeded 403 // so that the overhead exceeded does not persist. 404 405 const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded(); 406 const bool softrefs_clear = soft_ref_policy()->all_soft_refs_clear(); 407 408 if (limit_exceeded && softrefs_clear) { 409 *gc_overhead_limit_was_exceeded = true; 410 size_policy()->set_gc_overhead_limit_exceeded(false); 411 if (op.result() != NULL) { 412 CollectedHeap::fill_with_object(op.result(), size); 413 } 414 return NULL; 415 } 416 assert(result == NULL || is_in_reserved(result), 417 "result not in heap"); 418 return result; 419 } 420 421 // Give a warning if we seem to be looping forever. 422 if ((QueuedAllocationWarningCount > 0) && 423 (try_count % QueuedAllocationWarningCount == 0)) { 424 log_warning(gc, ergo)("GenCollectedHeap::mem_allocate_work retries %d times," 425 " size=" SIZE_FORMAT " %s", try_count, size, is_tlab ? "(TLAB)" : ""); 426 } 427 } 428 } 429 430 HeapWord* GenCollectedHeap::attempt_allocation(size_t size, 431 bool is_tlab, 432 bool first_only) { 433 HeapWord* res = NULL; 434 435 if (_young_gen->should_allocate(size, is_tlab)) { 436 res = _young_gen->allocate(size, is_tlab); 437 if (res != NULL || first_only) { 438 return res; 439 } 440 } 441 442 if (_old_gen->should_allocate(size, is_tlab)) { 443 res = _old_gen->allocate(size, is_tlab); 444 } 445 446 return res; 447 } 448 449 HeapWord* GenCollectedHeap::mem_allocate(size_t size, 450 bool* gc_overhead_limit_was_exceeded) { 451 return mem_allocate_work(size, 452 false /* is_tlab */, 453 gc_overhead_limit_was_exceeded); 454 } 455 456 bool GenCollectedHeap::must_clear_all_soft_refs() { 457 return _gc_cause == GCCause::_metadata_GC_clear_soft_refs || 458 _gc_cause == GCCause::_wb_full_gc; 459 } 460 461 void GenCollectedHeap::collect_generation(Generation* gen, bool full, size_t size, 462 bool is_tlab, bool run_verification, bool clear_soft_refs, 463 bool restore_marks_for_biased_locking) { 464 FormatBuffer<> title("Collect gen: %s", gen->short_name()); 465 GCTraceTime(Trace, gc, phases) t1(title); 466 TraceCollectorStats tcs(gen->counters()); 467 TraceMemoryManagerStats tmms(gen->gc_manager(), gc_cause()); 468 469 gen->stat_record()->invocations++; 470 gen->stat_record()->accumulated_time.start(); 471 472 // Must be done anew before each collection because 473 // a previous collection will do mangling and will 474 // change top of some spaces. 475 record_gen_tops_before_GC(); 476 477 log_trace(gc)("%s invoke=%d size=" SIZE_FORMAT, heap()->is_young_gen(gen) ? "Young" : "Old", gen->stat_record()->invocations, size * HeapWordSize); 478 479 if (run_verification && VerifyBeforeGC) { 480 HandleMark hm; // Discard invalid handles created during verification 481 Universe::verify("Before GC"); 482 } 483 COMPILER2_OR_JVMCI_PRESENT(DerivedPointerTable::clear()); 484 485 if (restore_marks_for_biased_locking) { 486 // We perform this mark word preservation work lazily 487 // because it's only at this point that we know whether we 488 // absolutely have to do it; we want to avoid doing it for 489 // scavenge-only collections where it's unnecessary 490 BiasedLocking::preserve_marks(); 491 } 492 493 // Do collection work 494 { 495 // Note on ref discovery: For what appear to be historical reasons, 496 // GCH enables and disabled (by enqueing) refs discovery. 497 // In the future this should be moved into the generation's 498 // collect method so that ref discovery and enqueueing concerns 499 // are local to a generation. The collect method could return 500 // an appropriate indication in the case that notification on 501 // the ref lock was needed. This will make the treatment of 502 // weak refs more uniform (and indeed remove such concerns 503 // from GCH). XXX 504 505 HandleMark hm; // Discard invalid handles created during gc 506 save_marks(); // save marks for all gens 507 // We want to discover references, but not process them yet. 508 // This mode is disabled in process_discovered_references if the 509 // generation does some collection work, or in 510 // enqueue_discovered_references if the generation returns 511 // without doing any work. 512 ReferenceProcessor* rp = gen->ref_processor(); 513 // If the discovery of ("weak") refs in this generation is 514 // atomic wrt other collectors in this configuration, we 515 // are guaranteed to have empty discovered ref lists. 516 if (rp->discovery_is_atomic()) { 517 rp->enable_discovery(); 518 rp->setup_policy(clear_soft_refs); 519 } else { 520 // collect() below will enable discovery as appropriate 521 } 522 gen->collect(full, clear_soft_refs, size, is_tlab); 523 if (!rp->enqueuing_is_done()) { 524 rp->disable_discovery(); 525 } else { 526 rp->set_enqueuing_is_done(false); 527 } 528 rp->verify_no_references_recorded(); 529 } 530 531 COMPILER2_OR_JVMCI_PRESENT(DerivedPointerTable::update_pointers()); 532 533 gen->stat_record()->accumulated_time.stop(); 534 535 update_gc_stats(gen, full); 536 537 if (run_verification && VerifyAfterGC) { 538 HandleMark hm; // Discard invalid handles created during verification 539 Universe::verify("After GC"); 540 } 541 } 542 543 void GenCollectedHeap::do_collection(bool full, 544 bool clear_all_soft_refs, 545 size_t size, 546 bool is_tlab, 547 GenerationType max_generation) { 548 ResourceMark rm; 549 DEBUG_ONLY(Thread* my_thread = Thread::current();) 550 551 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); 552 assert(my_thread->is_VM_thread() || 553 my_thread->is_ConcurrentGC_thread(), 554 "incorrect thread type capability"); 555 assert(Heap_lock->is_locked(), 556 "the requesting thread should have the Heap_lock"); 557 guarantee(!is_gc_active(), "collection is not reentrant"); 558 559 if (GCLocker::check_active_before_gc()) { 560 return; // GC is disabled (e.g. JNI GetXXXCritical operation) 561 } 562 563 const bool do_clear_all_soft_refs = clear_all_soft_refs || 564 soft_ref_policy()->should_clear_all_soft_refs(); 565 566 ClearedAllSoftRefs casr(do_clear_all_soft_refs, soft_ref_policy()); 567 568 AutoModifyRestore<bool> temporarily(_is_gc_active, true); 569 570 bool complete = full && (max_generation == OldGen); 571 bool old_collects_young = complete && !ScavengeBeforeFullGC; 572 bool do_young_collection = !old_collects_young && _young_gen->should_collect(full, size, is_tlab); 573 574 const PreGenGCValues pre_gc_values = get_pre_gc_values(); 575 576 bool run_verification = total_collections() >= VerifyGCStartAt; 577 bool prepared_for_verification = false; 578 bool do_full_collection = false; 579 580 if (do_young_collection) { 581 GCIdMark gc_id_mark; 582 GCTraceCPUTime tcpu; 583 GCTraceTime(Info, gc) t("Pause Young", NULL, gc_cause(), true); 584 585 print_heap_before_gc(); 586 587 if (run_verification && VerifyGCLevel <= 0 && VerifyBeforeGC) { 588 prepare_for_verify(); 589 prepared_for_verification = true; 590 } 591 592 gc_prologue(complete); 593 increment_total_collections(complete); 594 595 collect_generation(_young_gen, 596 full, 597 size, 598 is_tlab, 599 run_verification && VerifyGCLevel <= 0, 600 do_clear_all_soft_refs, 601 false); 602 603 if (size > 0 && (!is_tlab || _young_gen->supports_tlab_allocation()) && 604 size * HeapWordSize <= _young_gen->unsafe_max_alloc_nogc()) { 605 // Allocation request was met by young GC. 606 size = 0; 607 } 608 609 // Ask if young collection is enough. If so, do the final steps for young collection, 610 // and fallthrough to the end. 611 do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation); 612 if (!do_full_collection) { 613 // Adjust generation sizes. 614 _young_gen->compute_new_size(); 615 616 print_heap_change(pre_gc_values); 617 618 // Track memory usage and detect low memory after GC finishes 619 MemoryService::track_memory_usage(); 620 621 gc_epilogue(complete); 622 } 623 624 print_heap_after_gc(); 625 626 } else { 627 // No young collection, ask if we need to perform Full collection. 628 do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation); 629 } 630 631 if (do_full_collection) { 632 GCIdMark gc_id_mark; 633 GCTraceCPUTime tcpu; 634 GCTraceTime(Info, gc) t("Pause Full", NULL, gc_cause(), true); 635 636 print_heap_before_gc(); 637 638 if (!prepared_for_verification && run_verification && 639 VerifyGCLevel <= 1 && VerifyBeforeGC) { 640 prepare_for_verify(); 641 } 642 643 if (!do_young_collection) { 644 gc_prologue(complete); 645 increment_total_collections(complete); 646 } 647 648 // Accounting quirk: total full collections would be incremented when "complete" 649 // is set, by calling increment_total_collections above. However, we also need to 650 // account Full collections that had "complete" unset. 651 if (!complete) { 652 increment_total_full_collections(); 653 } 654 655 collect_generation(_old_gen, 656 full, 657 size, 658 is_tlab, 659 run_verification && VerifyGCLevel <= 1, 660 do_clear_all_soft_refs, 661 true); 662 663 // Adjust generation sizes. 664 _old_gen->compute_new_size(); 665 _young_gen->compute_new_size(); 666 667 // Delete metaspaces for unloaded class loaders and clean up loader_data graph 668 ClassLoaderDataGraph::purge(); 669 MetaspaceUtils::verify_metrics(); 670 // Resize the metaspace capacity after full collections 671 MetaspaceGC::compute_new_size(); 672 update_full_collections_completed(); 673 674 print_heap_change(pre_gc_values); 675 676 // Track memory usage and detect low memory after GC finishes 677 MemoryService::track_memory_usage(); 678 679 // Need to tell the epilogue code we are done with Full GC, regardless what was 680 // the initial value for "complete" flag. 681 gc_epilogue(true); 682 683 BiasedLocking::restore_marks(); 684 685 print_heap_after_gc(); 686 } 687 } 688 689 bool GenCollectedHeap::should_do_full_collection(size_t size, bool full, bool is_tlab, 690 GenCollectedHeap::GenerationType max_gen) const { 691 return max_gen == OldGen && _old_gen->should_collect(full, size, is_tlab); 692 } 693 694 void GenCollectedHeap::register_nmethod(nmethod* nm) { 695 ScavengableNMethods::register_nmethod(nm); 696 } 697 698 void GenCollectedHeap::unregister_nmethod(nmethod* nm) { 699 ScavengableNMethods::unregister_nmethod(nm); 700 } 701 702 void GenCollectedHeap::verify_nmethod(nmethod* nm) { 703 ScavengableNMethods::verify_nmethod(nm); 704 } 705 706 void GenCollectedHeap::flush_nmethod(nmethod* nm) { 707 // Do nothing. 708 } 709 710 void GenCollectedHeap::prune_scavengable_nmethods() { 711 ScavengableNMethods::prune_nmethods(); 712 } 713 714 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) { 715 GCCauseSetter x(this, GCCause::_allocation_failure); 716 HeapWord* result = NULL; 717 718 assert(size != 0, "Precondition violated"); 719 if (GCLocker::is_active_and_needs_gc()) { 720 // GC locker is active; instead of a collection we will attempt 721 // to expand the heap, if there's room for expansion. 722 if (!is_maximal_no_gc()) { 723 result = expand_heap_and_allocate(size, is_tlab); 724 } 725 return result; // Could be null if we are out of space. 726 } else if (!incremental_collection_will_fail(false /* don't consult_young */)) { 727 // Do an incremental collection. 728 do_collection(false, // full 729 false, // clear_all_soft_refs 730 size, // size 731 is_tlab, // is_tlab 732 GenCollectedHeap::OldGen); // max_generation 733 } else { 734 log_trace(gc)(" :: Trying full because partial may fail :: "); 735 // Try a full collection; see delta for bug id 6266275 736 // for the original code and why this has been simplified 737 // with from-space allocation criteria modified and 738 // such allocation moved out of the safepoint path. 739 do_collection(true, // full 740 false, // clear_all_soft_refs 741 size, // size 742 is_tlab, // is_tlab 743 GenCollectedHeap::OldGen); // max_generation 744 } 745 746 result = attempt_allocation(size, is_tlab, false /*first_only*/); 747 748 if (result != NULL) { 749 assert(is_in_reserved(result), "result not in heap"); 750 return result; 751 } 752 753 // OK, collection failed, try expansion. 754 result = expand_heap_and_allocate(size, is_tlab); 755 if (result != NULL) { 756 return result; 757 } 758 759 // If we reach this point, we're really out of memory. Try every trick 760 // we can to reclaim memory. Force collection of soft references. Force 761 // a complete compaction of the heap. Any additional methods for finding 762 // free memory should be here, especially if they are expensive. If this 763 // attempt fails, an OOM exception will be thrown. 764 { 765 UIntFlagSetting flag_change(MarkSweepAlwaysCompactCount, 1); // Make sure the heap is fully compacted 766 767 do_collection(true, // full 768 true, // clear_all_soft_refs 769 size, // size 770 is_tlab, // is_tlab 771 GenCollectedHeap::OldGen); // max_generation 772 } 773 774 result = attempt_allocation(size, is_tlab, false /* first_only */); 775 if (result != NULL) { 776 assert(is_in_reserved(result), "result not in heap"); 777 return result; 778 } 779 780 assert(!soft_ref_policy()->should_clear_all_soft_refs(), 781 "Flag should have been handled and cleared prior to this point"); 782 783 // What else? We might try synchronous finalization later. If the total 784 // space available is large enough for the allocation, then a more 785 // complete compaction phase than we've tried so far might be 786 // appropriate. 787 return NULL; 788 } 789 790 #ifdef ASSERT 791 class AssertNonScavengableClosure: public OopClosure { 792 public: 793 virtual void do_oop(oop* p) { 794 assert(!GenCollectedHeap::heap()->is_in_partial_collection(*p), 795 "Referent should not be scavengable."); } 796 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 797 }; 798 static AssertNonScavengableClosure assert_is_non_scavengable_closure; 799 #endif 800 801 void GenCollectedHeap::process_roots(StrongRootsScope* scope, 802 ScanningOption so, 803 OopClosure* strong_roots, 804 CLDClosure* strong_cld_closure, 805 CLDClosure* weak_cld_closure, 806 CodeBlobToOopClosure* code_roots) { 807 // General roots. 808 assert(code_roots != NULL, "code root closure should always be set"); 809 // _n_termination for _process_strong_tasks should be set up stream 810 // in a method not running in a GC worker. Otherwise the GC worker 811 // could be trying to change the termination condition while the task 812 // is executing in another GC worker. 813 814 if (_process_strong_tasks->try_claim_task(GCH_PS_ClassLoaderDataGraph_oops_do)) { 815 ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure); 816 } 817 818 // Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway 819 CodeBlobToOopClosure* roots_from_code_p = (so & SO_AllCodeCache) ? NULL : code_roots; 820 821 bool is_par = scope->n_threads() > 1; 822 Threads::possibly_parallel_oops_do(is_par, strong_roots, roots_from_code_p); 823 824 if (_process_strong_tasks->try_claim_task(GCH_PS_Universe_oops_do)) { 825 Universe::oops_do(strong_roots); 826 } 827 828 if (_process_strong_tasks->try_claim_task(GCH_PS_ObjectSynchronizer_oops_do)) { 829 ObjectSynchronizer::oops_do(strong_roots); 830 } 831 #if INCLUDE_AOT 832 if (UseAOT && _process_strong_tasks->try_claim_task(GCH_PS_aot_oops_do)) { 833 AOTLoader::oops_do(strong_roots); 834 } 835 #endif 836 if (_process_strong_tasks->try_claim_task(GCH_PS_OopStorageSet_oops_do)) { 837 OopStorageSet::strong_oops_do(strong_roots); 838 } 839 840 if (_process_strong_tasks->try_claim_task(GCH_PS_CodeCache_oops_do)) { 841 if (so & SO_ScavengeCodeCache) { 842 assert(code_roots != NULL, "must supply closure for code cache"); 843 844 // We only visit parts of the CodeCache when scavenging. 845 ScavengableNMethods::nmethods_do(code_roots); 846 } 847 if (so & SO_AllCodeCache) { 848 assert(code_roots != NULL, "must supply closure for code cache"); 849 850 // CMSCollector uses this to do intermediate-strength collections. 851 // We scan the entire code cache, since CodeCache::do_unloading is not called. 852 CodeCache::blobs_do(code_roots); 853 } 854 // Verify that the code cache contents are not subject to 855 // movement by a scavenging collection. 856 DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, !CodeBlobToOopClosure::FixRelocations)); 857 DEBUG_ONLY(ScavengableNMethods::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable)); 858 } 859 } 860 861 void GenCollectedHeap::young_process_roots(StrongRootsScope* scope, 862 OopsInGenClosure* root_closure, 863 OopsInGenClosure* old_gen_closure, 864 CLDClosure* cld_closure) { 865 MarkingCodeBlobClosure mark_code_closure(root_closure, CodeBlobToOopClosure::FixRelocations); 866 867 process_roots(scope, SO_ScavengeCodeCache, root_closure, 868 cld_closure, cld_closure, &mark_code_closure); 869 870 if (_process_strong_tasks->try_claim_task(GCH_PS_younger_gens)) { 871 root_closure->reset_generation(); 872 } 873 874 // When collection is parallel, all threads get to cooperate to do 875 // old generation scanning. 876 old_gen_closure->set_generation(_old_gen); 877 rem_set()->younger_refs_iterate(_old_gen, old_gen_closure, scope->n_threads()); 878 old_gen_closure->reset_generation(); 879 880 _process_strong_tasks->all_tasks_completed(scope->n_threads()); 881 } 882 883 void GenCollectedHeap::full_process_roots(StrongRootsScope* scope, 884 bool is_adjust_phase, 885 ScanningOption so, 886 bool only_strong_roots, 887 OopsInGenClosure* root_closure, 888 CLDClosure* cld_closure) { 889 MarkingCodeBlobClosure mark_code_closure(root_closure, is_adjust_phase); 890 CLDClosure* weak_cld_closure = only_strong_roots ? NULL : cld_closure; 891 892 process_roots(scope, so, root_closure, cld_closure, weak_cld_closure, &mark_code_closure); 893 _process_strong_tasks->all_tasks_completed(scope->n_threads()); 894 } 895 896 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) { 897 WeakProcessor::oops_do(root_closure); 898 _young_gen->ref_processor()->weak_oops_do(root_closure); 899 _old_gen->ref_processor()->weak_oops_do(root_closure); 900 } 901 902 bool GenCollectedHeap::no_allocs_since_save_marks() { 903 return _young_gen->no_allocs_since_save_marks() && 904 _old_gen->no_allocs_since_save_marks(); 905 } 906 907 bool GenCollectedHeap::supports_inline_contig_alloc() const { 908 return _young_gen->supports_inline_contig_alloc(); 909 } 910 911 HeapWord* volatile* GenCollectedHeap::top_addr() const { 912 return _young_gen->top_addr(); 913 } 914 915 HeapWord** GenCollectedHeap::end_addr() const { 916 return _young_gen->end_addr(); 917 } 918 919 // public collection interfaces 920 921 void GenCollectedHeap::collect(GCCause::Cause cause) { 922 if ((cause == GCCause::_wb_young_gc) || 923 (cause == GCCause::_gc_locker)) { 924 // Young collection for WhiteBox or GCLocker. 925 collect(cause, YoungGen); 926 } else { 927 #ifdef ASSERT 928 if (cause == GCCause::_scavenge_alot) { 929 // Young collection only. 930 collect(cause, YoungGen); 931 } else { 932 // Stop-the-world full collection. 933 collect(cause, OldGen); 934 } 935 #else 936 // Stop-the-world full collection. 937 collect(cause, OldGen); 938 #endif 939 } 940 } 941 942 void GenCollectedHeap::collect(GCCause::Cause cause, GenerationType max_generation) { 943 // The caller doesn't have the Heap_lock 944 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock"); 945 MutexLocker ml(Heap_lock); 946 collect_locked(cause, max_generation); 947 } 948 949 void GenCollectedHeap::collect_locked(GCCause::Cause cause) { 950 // The caller has the Heap_lock 951 assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock"); 952 collect_locked(cause, OldGen); 953 } 954 955 // this is the private collection interface 956 // The Heap_lock is expected to be held on entry. 957 958 void GenCollectedHeap::collect_locked(GCCause::Cause cause, GenerationType max_generation) { 959 // Read the GC count while holding the Heap_lock 960 unsigned int gc_count_before = total_collections(); 961 unsigned int full_gc_count_before = total_full_collections(); 962 963 if (GCLocker::should_discard(cause, gc_count_before)) { 964 return; 965 } 966 967 { 968 MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back 969 VM_GenCollectFull op(gc_count_before, full_gc_count_before, 970 cause, max_generation); 971 VMThread::execute(&op); 972 } 973 } 974 975 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) { 976 do_full_collection(clear_all_soft_refs, OldGen); 977 } 978 979 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs, 980 GenerationType last_generation) { 981 do_collection(true, // full 982 clear_all_soft_refs, // clear_all_soft_refs 983 0, // size 984 false, // is_tlab 985 last_generation); // last_generation 986 // Hack XXX FIX ME !!! 987 // A scavenge may not have been attempted, or may have 988 // been attempted and failed, because the old gen was too full 989 if (gc_cause() == GCCause::_gc_locker && incremental_collection_failed()) { 990 log_debug(gc, jni)("GC locker: Trying a full collection because scavenge failed"); 991 // This time allow the old gen to be collected as well 992 do_collection(true, // full 993 clear_all_soft_refs, // clear_all_soft_refs 994 0, // size 995 false, // is_tlab 996 OldGen); // last_generation 997 } 998 } 999 1000 bool GenCollectedHeap::is_in_young(oop p) { 1001 bool result = cast_from_oop<HeapWord*>(p) < _old_gen->reserved().start(); 1002 assert(result == _young_gen->is_in_reserved(p), 1003 "incorrect test - result=%d, p=" INTPTR_FORMAT, result, p2i((void*)p)); 1004 return result; 1005 } 1006 1007 // Returns "TRUE" iff "p" points into the committed areas of the heap. 1008 bool GenCollectedHeap::is_in(const void* p) const { 1009 return _young_gen->is_in(p) || _old_gen->is_in(p); 1010 } 1011 1012 #ifdef ASSERT 1013 // Don't implement this by using is_in_young(). This method is used 1014 // in some cases to check that is_in_young() is correct. 1015 bool GenCollectedHeap::is_in_partial_collection(const void* p) { 1016 assert(is_in_reserved(p) || p == NULL, 1017 "Does not work if address is non-null and outside of the heap"); 1018 return p < _young_gen->reserved().end() && p != NULL; 1019 } 1020 #endif 1021 1022 void GenCollectedHeap::oop_iterate(OopIterateClosure* cl) { 1023 _young_gen->oop_iterate(cl); 1024 _old_gen->oop_iterate(cl); 1025 } 1026 1027 void GenCollectedHeap::object_iterate(ObjectClosure* cl) { 1028 _young_gen->object_iterate(cl); 1029 _old_gen->object_iterate(cl); 1030 } 1031 1032 Space* GenCollectedHeap::space_containing(const void* addr) const { 1033 Space* res = _young_gen->space_containing(addr); 1034 if (res != NULL) { 1035 return res; 1036 } 1037 res = _old_gen->space_containing(addr); 1038 assert(res != NULL, "Could not find containing space"); 1039 return res; 1040 } 1041 1042 HeapWord* GenCollectedHeap::block_start(const void* addr) const { 1043 assert(is_in_reserved(addr), "block_start of address outside of heap"); 1044 if (_young_gen->is_in_reserved(addr)) { 1045 assert(_young_gen->is_in(addr), "addr should be in allocated part of generation"); 1046 return _young_gen->block_start(addr); 1047 } 1048 1049 assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address"); 1050 assert(_old_gen->is_in(addr), "addr should be in allocated part of generation"); 1051 return _old_gen->block_start(addr); 1052 } 1053 1054 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const { 1055 assert(is_in_reserved(addr), "block_is_obj of address outside of heap"); 1056 assert(block_start(addr) == addr, "addr must be a block start"); 1057 if (_young_gen->is_in_reserved(addr)) { 1058 return _young_gen->block_is_obj(addr); 1059 } 1060 1061 assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address"); 1062 return _old_gen->block_is_obj(addr); 1063 } 1064 1065 bool GenCollectedHeap::supports_tlab_allocation() const { 1066 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!"); 1067 return _young_gen->supports_tlab_allocation(); 1068 } 1069 1070 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const { 1071 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!"); 1072 if (_young_gen->supports_tlab_allocation()) { 1073 return _young_gen->tlab_capacity(); 1074 } 1075 return 0; 1076 } 1077 1078 size_t GenCollectedHeap::tlab_used(Thread* thr) const { 1079 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!"); 1080 if (_young_gen->supports_tlab_allocation()) { 1081 return _young_gen->tlab_used(); 1082 } 1083 return 0; 1084 } 1085 1086 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const { 1087 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!"); 1088 if (_young_gen->supports_tlab_allocation()) { 1089 return _young_gen->unsafe_max_tlab_alloc(); 1090 } 1091 return 0; 1092 } 1093 1094 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t min_size, 1095 size_t requested_size, 1096 size_t* actual_size) { 1097 bool gc_overhead_limit_was_exceeded; 1098 HeapWord* result = mem_allocate_work(requested_size /* size */, 1099 true /* is_tlab */, 1100 &gc_overhead_limit_was_exceeded); 1101 if (result != NULL) { 1102 *actual_size = requested_size; 1103 } 1104 1105 return result; 1106 } 1107 1108 // Requires "*prev_ptr" to be non-NULL. Deletes and a block of minimal size 1109 // from the list headed by "*prev_ptr". 1110 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) { 1111 bool first = true; 1112 size_t min_size = 0; // "first" makes this conceptually infinite. 1113 ScratchBlock **smallest_ptr, *smallest; 1114 ScratchBlock *cur = *prev_ptr; 1115 while (cur) { 1116 assert(*prev_ptr == cur, "just checking"); 1117 if (first || cur->num_words < min_size) { 1118 smallest_ptr = prev_ptr; 1119 smallest = cur; 1120 min_size = smallest->num_words; 1121 first = false; 1122 } 1123 prev_ptr = &cur->next; 1124 cur = cur->next; 1125 } 1126 smallest = *smallest_ptr; 1127 *smallest_ptr = smallest->next; 1128 return smallest; 1129 } 1130 1131 // Sort the scratch block list headed by res into decreasing size order, 1132 // and set "res" to the result. 1133 static void sort_scratch_list(ScratchBlock*& list) { 1134 ScratchBlock* sorted = NULL; 1135 ScratchBlock* unsorted = list; 1136 while (unsorted) { 1137 ScratchBlock *smallest = removeSmallestScratch(&unsorted); 1138 smallest->next = sorted; 1139 sorted = smallest; 1140 } 1141 list = sorted; 1142 } 1143 1144 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor, 1145 size_t max_alloc_words) { 1146 ScratchBlock* res = NULL; 1147 _young_gen->contribute_scratch(res, requestor, max_alloc_words); 1148 _old_gen->contribute_scratch(res, requestor, max_alloc_words); 1149 sort_scratch_list(res); 1150 return res; 1151 } 1152 1153 void GenCollectedHeap::release_scratch() { 1154 _young_gen->reset_scratch(); 1155 _old_gen->reset_scratch(); 1156 } 1157 1158 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure { 1159 void do_generation(Generation* gen) { 1160 gen->prepare_for_verify(); 1161 } 1162 }; 1163 1164 void GenCollectedHeap::prepare_for_verify() { 1165 ensure_parsability(false); // no need to retire TLABs 1166 GenPrepareForVerifyClosure blk; 1167 generation_iterate(&blk, false); 1168 } 1169 1170 void GenCollectedHeap::generation_iterate(GenClosure* cl, 1171 bool old_to_young) { 1172 if (old_to_young) { 1173 cl->do_generation(_old_gen); 1174 cl->do_generation(_young_gen); 1175 } else { 1176 cl->do_generation(_young_gen); 1177 cl->do_generation(_old_gen); 1178 } 1179 } 1180 1181 bool GenCollectedHeap::is_maximal_no_gc() const { 1182 return _young_gen->is_maximal_no_gc() && _old_gen->is_maximal_no_gc(); 1183 } 1184 1185 void GenCollectedHeap::save_marks() { 1186 _young_gen->save_marks(); 1187 _old_gen->save_marks(); 1188 } 1189 1190 GenCollectedHeap* GenCollectedHeap::heap() { 1191 // SerialHeap is the only subtype of GenCollectedHeap. 1192 return named_heap<GenCollectedHeap>(CollectedHeap::Serial); 1193 } 1194 1195 #if INCLUDE_SERIALGC 1196 void GenCollectedHeap::prepare_for_compaction() { 1197 // Start by compacting into same gen. 1198 CompactPoint cp(_old_gen); 1199 _old_gen->prepare_for_compaction(&cp); 1200 _young_gen->prepare_for_compaction(&cp); 1201 } 1202 #endif // INCLUDE_SERIALGC 1203 1204 void GenCollectedHeap::verify(VerifyOption option /* ignored */) { 1205 log_debug(gc, verify)("%s", _old_gen->name()); 1206 _old_gen->verify(); 1207 1208 log_debug(gc, verify)("%s", _old_gen->name()); 1209 _young_gen->verify(); 1210 1211 log_debug(gc, verify)("RemSet"); 1212 rem_set()->verify(); 1213 } 1214 1215 void GenCollectedHeap::print_on(outputStream* st) const { 1216 if (_young_gen != NULL) { 1217 _young_gen->print_on(st); 1218 } 1219 if (_old_gen != NULL) { 1220 _old_gen->print_on(st); 1221 } 1222 MetaspaceUtils::print_on(st); 1223 } 1224 1225 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const { 1226 } 1227 1228 bool GenCollectedHeap::print_location(outputStream* st, void* addr) const { 1229 return BlockLocationPrinter<GenCollectedHeap>::print_location(st, addr); 1230 } 1231 1232 void GenCollectedHeap::print_tracing_info() const { 1233 if (log_is_enabled(Debug, gc, heap, exit)) { 1234 LogStreamHandle(Debug, gc, heap, exit) lsh; 1235 _young_gen->print_summary_info_on(&lsh); 1236 _old_gen->print_summary_info_on(&lsh); 1237 } 1238 } 1239 1240 void GenCollectedHeap::print_heap_change(const PreGenGCValues& pre_gc_values) const { 1241 const DefNewGeneration* const def_new_gen = (DefNewGeneration*) young_gen(); 1242 1243 log_info(gc, heap)(HEAP_CHANGE_FORMAT" " 1244 HEAP_CHANGE_FORMAT" " 1245 HEAP_CHANGE_FORMAT, 1246 HEAP_CHANGE_FORMAT_ARGS(def_new_gen->short_name(), 1247 pre_gc_values.young_gen_used(), 1248 pre_gc_values.young_gen_capacity(), 1249 def_new_gen->used(), 1250 def_new_gen->capacity()), 1251 HEAP_CHANGE_FORMAT_ARGS("Eden", 1252 pre_gc_values.eden_used(), 1253 pre_gc_values.eden_capacity(), 1254 def_new_gen->eden()->used(), 1255 def_new_gen->eden()->capacity()), 1256 HEAP_CHANGE_FORMAT_ARGS("From", 1257 pre_gc_values.from_used(), 1258 pre_gc_values.from_capacity(), 1259 def_new_gen->from()->used(), 1260 def_new_gen->from()->capacity())); 1261 log_info(gc, heap)(HEAP_CHANGE_FORMAT, 1262 HEAP_CHANGE_FORMAT_ARGS(old_gen()->short_name(), 1263 pre_gc_values.old_gen_used(), 1264 pre_gc_values.old_gen_capacity(), 1265 old_gen()->used(), 1266 old_gen()->capacity())); 1267 MetaspaceUtils::print_metaspace_change(pre_gc_values.metaspace_sizes()); 1268 } 1269 1270 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure { 1271 private: 1272 bool _full; 1273 public: 1274 void do_generation(Generation* gen) { 1275 gen->gc_prologue(_full); 1276 } 1277 GenGCPrologueClosure(bool full) : _full(full) {}; 1278 }; 1279 1280 void GenCollectedHeap::gc_prologue(bool full) { 1281 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer"); 1282 1283 // Fill TLAB's and such 1284 ensure_parsability(true); // retire TLABs 1285 1286 // Walk generations 1287 GenGCPrologueClosure blk(full); 1288 generation_iterate(&blk, false); // not old-to-young. 1289 }; 1290 1291 class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure { 1292 private: 1293 bool _full; 1294 public: 1295 void do_generation(Generation* gen) { 1296 gen->gc_epilogue(_full); 1297 } 1298 GenGCEpilogueClosure(bool full) : _full(full) {}; 1299 }; 1300 1301 void GenCollectedHeap::gc_epilogue(bool full) { 1302 #if COMPILER2_OR_JVMCI 1303 assert(DerivedPointerTable::is_empty(), "derived pointer present"); 1304 size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr())); 1305 guarantee(is_client_compilation_mode_vm() || actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps"); 1306 #endif // COMPILER2_OR_JVMCI 1307 1308 resize_all_tlabs(); 1309 1310 GenGCEpilogueClosure blk(full); 1311 generation_iterate(&blk, false); // not old-to-young. 1312 1313 if (!CleanChunkPoolAsync) { 1314 Chunk::clean_chunk_pool(); 1315 } 1316 1317 MetaspaceCounters::update_performance_counters(); 1318 CompressedClassSpaceCounters::update_performance_counters(); 1319 }; 1320 1321 #ifndef PRODUCT 1322 class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure { 1323 private: 1324 public: 1325 void do_generation(Generation* gen) { 1326 gen->record_spaces_top(); 1327 } 1328 }; 1329 1330 void GenCollectedHeap::record_gen_tops_before_GC() { 1331 if (ZapUnusedHeapArea) { 1332 GenGCSaveTopsBeforeGCClosure blk; 1333 generation_iterate(&blk, false); // not old-to-young. 1334 } 1335 } 1336 #endif // not PRODUCT 1337 1338 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure { 1339 public: 1340 void do_generation(Generation* gen) { 1341 gen->ensure_parsability(); 1342 } 1343 }; 1344 1345 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) { 1346 CollectedHeap::ensure_parsability(retire_tlabs); 1347 GenEnsureParsabilityClosure ep_cl; 1348 generation_iterate(&ep_cl, false); 1349 } 1350 1351 oop GenCollectedHeap::handle_failed_promotion(Generation* old_gen, 1352 oop obj, 1353 size_t obj_size) { 1354 guarantee(old_gen == _old_gen, "We only get here with an old generation"); 1355 assert(obj_size == (size_t)obj->size(), "bad obj_size passed in"); 1356 HeapWord* result = NULL; 1357 1358 result = old_gen->expand_and_allocate(obj_size, false); 1359 1360 if (result != NULL) { 1361 Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(obj), result, obj_size); 1362 } 1363 return oop(result); 1364 } 1365 1366 class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure { 1367 jlong _time; // in ms 1368 jlong _now; // in ms 1369 1370 public: 1371 GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { } 1372 1373 jlong time() { return _time; } 1374 1375 void do_generation(Generation* gen) { 1376 _time = MIN2(_time, gen->time_of_last_gc(_now)); 1377 } 1378 }; 1379 1380 jlong GenCollectedHeap::millis_since_last_gc() { 1381 // javaTimeNanos() is guaranteed to be monotonically non-decreasing 1382 // provided the underlying platform provides such a time source 1383 // (and it is bug free). So we still have to guard against getting 1384 // back a time later than 'now'. 1385 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC; 1386 GenTimeOfLastGCClosure tolgc_cl(now); 1387 // iterate over generations getting the oldest 1388 // time that a generation was collected 1389 generation_iterate(&tolgc_cl, false); 1390 1391 jlong retVal = now - tolgc_cl.time(); 1392 if (retVal < 0) { 1393 log_warning(gc)("millis_since_last_gc() would return : " JLONG_FORMAT 1394 ". returning zero instead.", retVal); 1395 return 0; 1396 } 1397 return retVal; 1398 }