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