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