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