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