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