1 /* 2 * Copyright (c) 2000, 2017, 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/collectedHeap.inline.hpp" 34 #include "gc/shared/collectorCounters.hpp" 35 #include "gc/shared/gcId.hpp" 36 #include "gc/shared/gcLocker.inline.hpp" 37 #include "gc/shared/gcTrace.hpp" 38 #include "gc/shared/gcTraceTime.inline.hpp" 39 #include "gc/shared/genCollectedHeap.hpp" 40 #include "gc/shared/genOopClosures.inline.hpp" 41 #include "gc/shared/generationSpec.hpp" 42 #include "gc/shared/space.hpp" 43 #include "gc/shared/strongRootsScope.hpp" 44 #include "gc/shared/vmGCOperations.hpp" 45 #include "gc/shared/weakProcessor.hpp" 46 #include "gc/shared/workgroup.hpp" 47 #include "memory/filemap.hpp" 48 #include "memory/resourceArea.hpp" 49 #include "oops/oop.inline.hpp" 50 #include "runtime/biasedLocking.hpp" 51 #include "runtime/handles.hpp" 52 #include "runtime/handles.inline.hpp" 53 #include "runtime/java.hpp" 54 #include "runtime/vmThread.hpp" 55 #include "services/management.hpp" 56 #include "services/memoryService.hpp" 57 #include "utilities/debug.hpp" 58 #include "utilities/formatBuffer.hpp" 59 #include "utilities/macros.hpp" 60 #include "utilities/stack.inline.hpp" 61 #include "utilities/vmError.hpp" 62 63 GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy) : 64 CollectedHeap(), 65 _rem_set(NULL), 66 _gen_policy(policy), 67 _process_strong_tasks(new SubTasksDone(GCH_PS_NumElements)), 68 _full_collections_completed(0) 69 { 70 assert(policy != NULL, "Sanity check"); 71 } 72 73 jint GenCollectedHeap::initialize() { 74 CollectedHeap::pre_initialize(); 75 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 = collector_policy()->create_rem_set(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 _gen_policy->initialize_gc_policy_counters(); 155 } 156 157 void GenCollectedHeap::ref_processing_init() { 158 _young_gen->ref_processor_init(); 159 _old_gen->ref_processor_init(); 160 } 161 162 size_t GenCollectedHeap::capacity() const { 163 return _young_gen->capacity() + _old_gen->capacity(); 164 } 165 166 size_t GenCollectedHeap::used() const { 167 return _young_gen->used() + _old_gen->used(); 168 } 169 170 void GenCollectedHeap::save_used_regions() { 171 _old_gen->save_used_region(); 172 _young_gen->save_used_region(); 173 } 174 175 size_t GenCollectedHeap::max_capacity() const { 176 return _young_gen->max_capacity() + _old_gen->max_capacity(); 177 } 178 179 // Update the _full_collections_completed counter 180 // at the end of a stop-world full GC. 181 unsigned int GenCollectedHeap::update_full_collections_completed() { 182 MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag); 183 assert(_full_collections_completed <= _total_full_collections, 184 "Can't complete more collections than were started"); 185 _full_collections_completed = _total_full_collections; 186 ml.notify_all(); 187 return _full_collections_completed; 188 } 189 190 // Update the _full_collections_completed counter, as appropriate, 191 // at the end of a concurrent GC cycle. Note the conditional update 192 // below to allow this method to be called by a concurrent collector 193 // without synchronizing in any manner with the VM thread (which 194 // may already have initiated a STW full collection "concurrently"). 195 unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) { 196 MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag); 197 assert((_full_collections_completed <= _total_full_collections) && 198 (count <= _total_full_collections), 199 "Can't complete more collections than were started"); 200 if (count > _full_collections_completed) { 201 _full_collections_completed = count; 202 ml.notify_all(); 203 } 204 return _full_collections_completed; 205 } 206 207 208 #ifndef PRODUCT 209 // Override of memory state checking method in CollectedHeap: 210 // Some collectors (CMS for example) can't have badHeapWordVal written 211 // in the first two words of an object. (For instance , in the case of 212 // CMS these words hold state used to synchronize between certain 213 // (concurrent) GC steps and direct allocating mutators.) 214 // The skip_header_HeapWords() method below, allows us to skip 215 // over the requisite number of HeapWord's. Note that (for 216 // generational collectors) this means that those many words are 217 // skipped in each object, irrespective of the generation in which 218 // that object lives. The resultant loss of precision seems to be 219 // harmless and the pain of avoiding that imprecision appears somewhat 220 // higher than we are prepared to pay for such rudimentary debugging 221 // support. 222 void GenCollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr, 223 size_t size) { 224 if (CheckMemoryInitialization && ZapUnusedHeapArea) { 225 // We are asked to check a size in HeapWords, 226 // but the memory is mangled in juint words. 227 juint* start = (juint*) (addr + skip_header_HeapWords()); 228 juint* end = (juint*) (addr + size); 229 for (juint* slot = start; slot < end; slot += 1) { 230 assert(*slot == badHeapWordVal, 231 "Found non badHeapWordValue in pre-allocation check"); 232 } 233 } 234 } 235 #endif 236 237 HeapWord* GenCollectedHeap::attempt_allocation(size_t size, 238 bool is_tlab, 239 bool first_only) { 240 HeapWord* res = NULL; 241 242 if (_young_gen->should_allocate(size, is_tlab)) { 243 res = _young_gen->allocate(size, is_tlab); 244 if (res != NULL || first_only) { 245 return res; 246 } 247 } 248 249 if (_old_gen->should_allocate(size, is_tlab)) { 250 res = _old_gen->allocate(size, is_tlab); 251 } 252 253 return res; 254 } 255 256 HeapWord* GenCollectedHeap::mem_allocate(size_t size, 257 bool* gc_overhead_limit_was_exceeded) { 258 return gen_policy()->mem_allocate_work(size, 259 false /* is_tlab */, 260 gc_overhead_limit_was_exceeded); 261 } 262 263 bool GenCollectedHeap::must_clear_all_soft_refs() { 264 return _gc_cause == GCCause::_metadata_GC_clear_soft_refs || 265 _gc_cause == GCCause::_wb_full_gc; 266 } 267 268 void GenCollectedHeap::collect_generation(Generation* gen, bool full, size_t size, 269 bool is_tlab, bool run_verification, bool clear_soft_refs, 270 bool restore_marks_for_biased_locking) { 271 FormatBuffer<> title("Collect gen: %s", gen->short_name()); 272 GCTraceTime(Trace, gc, phases) t1(title); 273 TraceCollectorStats tcs(gen->counters()); 274 TraceMemoryManagerStats tmms(gen->gc_manager(), gc_cause()); 275 276 gen->stat_record()->invocations++; 277 gen->stat_record()->accumulated_time.start(); 278 279 // Must be done anew before each collection because 280 // a previous collection will do mangling and will 281 // change top of some spaces. 282 record_gen_tops_before_GC(); 283 284 log_trace(gc)("%s invoke=%d size=" SIZE_FORMAT, heap()->is_young_gen(gen) ? "Young" : "Old", gen->stat_record()->invocations, size * HeapWordSize); 285 286 if (run_verification && VerifyBeforeGC) { 287 HandleMark hm; // Discard invalid handles created during verification 288 Universe::verify("Before GC"); 289 } 290 COMPILER2_PRESENT(DerivedPointerTable::clear()); 291 292 if (restore_marks_for_biased_locking) { 293 // We perform this mark word preservation work lazily 294 // because it's only at this point that we know whether we 295 // absolutely have to do it; we want to avoid doing it for 296 // scavenge-only collections where it's unnecessary 297 BiasedLocking::preserve_marks(); 298 } 299 300 // Do collection work 301 { 302 // Note on ref discovery: For what appear to be historical reasons, 303 // GCH enables and disabled (by enqueing) refs discovery. 304 // In the future this should be moved into the generation's 305 // collect method so that ref discovery and enqueueing concerns 306 // are local to a generation. The collect method could return 307 // an appropriate indication in the case that notification on 308 // the ref lock was needed. This will make the treatment of 309 // weak refs more uniform (and indeed remove such concerns 310 // from GCH). XXX 311 312 HandleMark hm; // Discard invalid handles created during gc 313 save_marks(); // save marks for all gens 314 // We want to discover references, but not process them yet. 315 // This mode is disabled in process_discovered_references if the 316 // generation does some collection work, or in 317 // enqueue_discovered_references if the generation returns 318 // without doing any work. 319 ReferenceProcessor* rp = gen->ref_processor(); 320 // If the discovery of ("weak") refs in this generation is 321 // atomic wrt other collectors in this configuration, we 322 // are guaranteed to have empty discovered ref lists. 323 if (rp->discovery_is_atomic()) { 324 rp->enable_discovery(); 325 rp->setup_policy(clear_soft_refs); 326 } else { 327 // collect() below will enable discovery as appropriate 328 } 329 gen->collect(full, clear_soft_refs, size, is_tlab); 330 if (!rp->enqueuing_is_done()) { 331 ReferenceProcessorPhaseTimes pt(NULL, rp->num_q()); 332 rp->enqueue_discovered_references(NULL, &pt); 333 pt.print_enqueue_phase(); 334 } else { 335 rp->set_enqueuing_is_done(false); 336 } 337 rp->verify_no_references_recorded(); 338 } 339 340 COMPILER2_PRESENT(DerivedPointerTable::update_pointers()); 341 342 gen->stat_record()->accumulated_time.stop(); 343 344 update_gc_stats(gen, full); 345 346 if (run_verification && VerifyAfterGC) { 347 HandleMark hm; // Discard invalid handles created during verification 348 Universe::verify("After GC"); 349 } 350 } 351 352 void GenCollectedHeap::do_collection(bool full, 353 bool clear_all_soft_refs, 354 size_t size, 355 bool is_tlab, 356 GenerationType max_generation) { 357 ResourceMark rm; 358 DEBUG_ONLY(Thread* my_thread = Thread::current();) 359 360 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); 361 assert(my_thread->is_VM_thread() || 362 my_thread->is_ConcurrentGC_thread(), 363 "incorrect thread type capability"); 364 assert(Heap_lock->is_locked(), 365 "the requesting thread should have the Heap_lock"); 366 guarantee(!is_gc_active(), "collection is not reentrant"); 367 368 if (GCLocker::check_active_before_gc()) { 369 return; // GC is disabled (e.g. JNI GetXXXCritical operation) 370 } 371 372 GCIdMarkAndRestore gc_id_mark; 373 374 const bool do_clear_all_soft_refs = clear_all_soft_refs || 375 collector_policy()->should_clear_all_soft_refs(); 376 377 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy()); 378 379 const size_t metadata_prev_used = MetaspaceAux::used_bytes(); 380 381 print_heap_before_gc(); 382 383 { 384 FlagSetting fl(_is_gc_active, true); 385 386 bool complete = full && (max_generation == OldGen); 387 bool old_collects_young = complete && !ScavengeBeforeFullGC; 388 bool do_young_collection = !old_collects_young && _young_gen->should_collect(full, size, is_tlab); 389 390 FormatBuffer<> gc_string("%s", "Pause "); 391 if (do_young_collection) { 392 gc_string.append("Young"); 393 } else { 394 gc_string.append("Full"); 395 } 396 397 GCTraceCPUTime tcpu; 398 GCTraceTime(Info, gc) t(gc_string, NULL, gc_cause(), true); 399 400 gc_prologue(complete); 401 increment_total_collections(complete); 402 403 size_t young_prev_used = _young_gen->used(); 404 size_t old_prev_used = _old_gen->used(); 405 406 bool run_verification = total_collections() >= VerifyGCStartAt; 407 408 bool prepared_for_verification = false; 409 bool collected_old = false; 410 411 if (do_young_collection) { 412 if (run_verification && VerifyGCLevel <= 0 && VerifyBeforeGC) { 413 prepare_for_verify(); 414 prepared_for_verification = true; 415 } 416 417 collect_generation(_young_gen, 418 full, 419 size, 420 is_tlab, 421 run_verification && VerifyGCLevel <= 0, 422 do_clear_all_soft_refs, 423 false); 424 425 if (size > 0 && (!is_tlab || _young_gen->supports_tlab_allocation()) && 426 size * HeapWordSize <= _young_gen->unsafe_max_alloc_nogc()) { 427 // Allocation request was met by young GC. 428 size = 0; 429 } 430 } 431 432 bool must_restore_marks_for_biased_locking = false; 433 434 if (max_generation == OldGen && _old_gen->should_collect(full, size, is_tlab)) { 435 if (!complete) { 436 // The full_collections increment was missed above. 437 increment_total_full_collections(); 438 } 439 440 if (!prepared_for_verification && run_verification && 441 VerifyGCLevel <= 1 && VerifyBeforeGC) { 442 prepare_for_verify(); 443 } 444 445 if (do_young_collection) { 446 // We did a young GC. Need a new GC id for the old GC. 447 GCIdMarkAndRestore gc_id_mark; 448 GCTraceTime(Info, gc) t("Pause Full", NULL, gc_cause(), true); 449 collect_generation(_old_gen, full, size, is_tlab, run_verification && VerifyGCLevel <= 1, do_clear_all_soft_refs, true); 450 } else { 451 // No young GC done. Use the same GC id as was set up earlier in this method. 452 collect_generation(_old_gen, full, size, is_tlab, run_verification && VerifyGCLevel <= 1, do_clear_all_soft_refs, true); 453 } 454 455 must_restore_marks_for_biased_locking = true; 456 collected_old = true; 457 } 458 459 // Update "complete" boolean wrt what actually transpired -- 460 // for instance, a promotion failure could have led to 461 // a whole heap collection. 462 complete = complete || collected_old; 463 464 print_heap_change(young_prev_used, old_prev_used); 465 MetaspaceAux::print_metaspace_change(metadata_prev_used); 466 467 // Adjust generation sizes. 468 if (collected_old) { 469 _old_gen->compute_new_size(); 470 } 471 _young_gen->compute_new_size(); 472 473 if (complete) { 474 // Delete metaspaces for unloaded class loaders and clean up loader_data graph 475 ClassLoaderDataGraph::purge(); 476 MetaspaceAux::verify_metrics(); 477 // Resize the metaspace capacity after full collections 478 MetaspaceGC::compute_new_size(); 479 update_full_collections_completed(); 480 } 481 482 // Track memory usage and detect low memory after GC finishes 483 MemoryService::track_memory_usage(); 484 485 gc_epilogue(complete); 486 487 if (must_restore_marks_for_biased_locking) { 488 BiasedLocking::restore_marks(); 489 } 490 } 491 492 print_heap_after_gc(); 493 494 #ifdef TRACESPINNING 495 ParallelTaskTerminator::print_termination_counts(); 496 #endif 497 } 498 499 void GenCollectedHeap::register_nmethod(nmethod* nm) { 500 CodeCache::register_scavenge_root_nmethod(nm); 501 } 502 503 void GenCollectedHeap::verify_nmethod(nmethod* nm) { 504 CodeCache::verify_scavenge_root_nmethod(nm); 505 } 506 507 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) { 508 return gen_policy()->satisfy_failed_allocation(size, is_tlab); 509 } 510 511 #ifdef ASSERT 512 class AssertNonScavengableClosure: public OopClosure { 513 public: 514 virtual void do_oop(oop* p) { 515 assert(!GenCollectedHeap::heap()->is_in_partial_collection(*p), 516 "Referent should not be scavengable."); } 517 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 518 }; 519 static AssertNonScavengableClosure assert_is_non_scavengable_closure; 520 #endif 521 522 void GenCollectedHeap::process_roots(StrongRootsScope* scope, 523 ScanningOption so, 524 OopClosure* strong_roots, 525 OopClosure* weak_roots, 526 CLDClosure* strong_cld_closure, 527 CLDClosure* weak_cld_closure, 528 CodeBlobToOopClosure* code_roots) { 529 // General roots. 530 assert(Threads::thread_claim_parity() != 0, "must have called prologue code"); 531 assert(code_roots != NULL, "code root closure should always be set"); 532 // _n_termination for _process_strong_tasks should be set up stream 533 // in a method not running in a GC worker. Otherwise the GC worker 534 // could be trying to change the termination condition while the task 535 // is executing in another GC worker. 536 537 if (!_process_strong_tasks->is_task_claimed(GCH_PS_ClassLoaderDataGraph_oops_do)) { 538 ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure); 539 } 540 541 // Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway 542 CodeBlobToOopClosure* roots_from_code_p = (so & SO_AllCodeCache) ? NULL : code_roots; 543 544 bool is_par = scope->n_threads() > 1; 545 Threads::possibly_parallel_oops_do(is_par, strong_roots, roots_from_code_p); 546 547 if (!_process_strong_tasks->is_task_claimed(GCH_PS_Universe_oops_do)) { 548 Universe::oops_do(strong_roots); 549 } 550 // Global (strong) JNI handles 551 if (!_process_strong_tasks->is_task_claimed(GCH_PS_JNIHandles_oops_do)) { 552 JNIHandles::oops_do(strong_roots); 553 } 554 555 if (!_process_strong_tasks->is_task_claimed(GCH_PS_ObjectSynchronizer_oops_do)) { 556 ObjectSynchronizer::oops_do(strong_roots); 557 } 558 if (!_process_strong_tasks->is_task_claimed(GCH_PS_Management_oops_do)) { 559 Management::oops_do(strong_roots); 560 } 561 if (!_process_strong_tasks->is_task_claimed(GCH_PS_jvmti_oops_do)) { 562 JvmtiExport::oops_do(strong_roots); 563 } 564 if (UseAOT && !_process_strong_tasks->is_task_claimed(GCH_PS_aot_oops_do)) { 565 AOTLoader::oops_do(strong_roots); 566 } 567 568 if (!_process_strong_tasks->is_task_claimed(GCH_PS_SystemDictionary_oops_do)) { 569 SystemDictionary::roots_oops_do(strong_roots, weak_roots); 570 } 571 572 if (!_process_strong_tasks->is_task_claimed(GCH_PS_CodeCache_oops_do)) { 573 if (so & SO_ScavengeCodeCache) { 574 assert(code_roots != NULL, "must supply closure for code cache"); 575 576 // We only visit parts of the CodeCache when scavenging. 577 CodeCache::scavenge_root_nmethods_do(code_roots); 578 } 579 if (so & SO_AllCodeCache) { 580 assert(code_roots != NULL, "must supply closure for code cache"); 581 582 // CMSCollector uses this to do intermediate-strength collections. 583 // We scan the entire code cache, since CodeCache::do_unloading is not called. 584 CodeCache::blobs_do(code_roots); 585 } 586 // Verify that the code cache contents are not subject to 587 // movement by a scavenging collection. 588 DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, !CodeBlobToOopClosure::FixRelocations)); 589 DEBUG_ONLY(CodeCache::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable)); 590 } 591 } 592 593 void GenCollectedHeap::process_string_table_roots(StrongRootsScope* scope, 594 OopClosure* root_closure) { 595 assert(root_closure != NULL, "Must be set"); 596 // All threads execute the following. A specific chunk of buckets 597 // from the StringTable are the individual tasks. 598 if (scope->n_threads() > 1) { 599 StringTable::possibly_parallel_oops_do(root_closure); 600 } else { 601 StringTable::oops_do(root_closure); 602 } 603 } 604 605 void GenCollectedHeap::young_process_roots(StrongRootsScope* scope, 606 OopsInGenClosure* root_closure, 607 OopsInGenClosure* old_gen_closure, 608 CLDClosure* cld_closure) { 609 MarkingCodeBlobClosure mark_code_closure(root_closure, CodeBlobToOopClosure::FixRelocations); 610 611 process_roots(scope, SO_ScavengeCodeCache, root_closure, root_closure, 612 cld_closure, cld_closure, &mark_code_closure); 613 process_string_table_roots(scope, root_closure); 614 615 if (!_process_strong_tasks->is_task_claimed(GCH_PS_younger_gens)) { 616 root_closure->reset_generation(); 617 } 618 619 // When collection is parallel, all threads get to cooperate to do 620 // old generation scanning. 621 old_gen_closure->set_generation(_old_gen); 622 rem_set()->younger_refs_iterate(_old_gen, old_gen_closure, scope->n_threads()); 623 old_gen_closure->reset_generation(); 624 625 _process_strong_tasks->all_tasks_completed(scope->n_threads()); 626 } 627 628 void GenCollectedHeap::full_process_roots(StrongRootsScope* scope, 629 bool is_adjust_phase, 630 ScanningOption so, 631 bool only_strong_roots, 632 OopsInGenClosure* root_closure, 633 CLDClosure* cld_closure) { 634 MarkingCodeBlobClosure mark_code_closure(root_closure, is_adjust_phase); 635 OopsInGenClosure* weak_roots = only_strong_roots ? NULL : root_closure; 636 CLDClosure* weak_cld_closure = only_strong_roots ? NULL : cld_closure; 637 638 process_roots(scope, so, root_closure, weak_roots, cld_closure, weak_cld_closure, &mark_code_closure); 639 if (is_adjust_phase) { 640 // We never treat the string table as roots during marking 641 // for the full gc, so we only need to process it during 642 // the adjust phase. 643 process_string_table_roots(scope, root_closure); 644 } 645 646 _process_strong_tasks->all_tasks_completed(scope->n_threads()); 647 } 648 649 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) { 650 WeakProcessor::oops_do(root_closure); 651 _young_gen->ref_processor()->weak_oops_do(root_closure); 652 _old_gen->ref_processor()->weak_oops_do(root_closure); 653 } 654 655 #define GCH_SINCE_SAVE_MARKS_ITERATE_DEFN(OopClosureType, nv_suffix) \ 656 void GenCollectedHeap:: \ 657 oop_since_save_marks_iterate(GenerationType gen, \ 658 OopClosureType* cur, \ 659 OopClosureType* older) { \ 660 if (gen == YoungGen) { \ 661 _young_gen->oop_since_save_marks_iterate##nv_suffix(cur); \ 662 _old_gen->oop_since_save_marks_iterate##nv_suffix(older); \ 663 } else { \ 664 _old_gen->oop_since_save_marks_iterate##nv_suffix(cur); \ 665 } \ 666 } 667 668 ALL_SINCE_SAVE_MARKS_CLOSURES(GCH_SINCE_SAVE_MARKS_ITERATE_DEFN) 669 670 #undef GCH_SINCE_SAVE_MARKS_ITERATE_DEFN 671 672 bool GenCollectedHeap::no_allocs_since_save_marks() { 673 return _young_gen->no_allocs_since_save_marks() && 674 _old_gen->no_allocs_since_save_marks(); 675 } 676 677 bool GenCollectedHeap::supports_inline_contig_alloc() const { 678 return _young_gen->supports_inline_contig_alloc(); 679 } 680 681 HeapWord* volatile* GenCollectedHeap::top_addr() const { 682 return _young_gen->top_addr(); 683 } 684 685 HeapWord** GenCollectedHeap::end_addr() const { 686 return _young_gen->end_addr(); 687 } 688 689 // public collection interfaces 690 691 void GenCollectedHeap::collect(GCCause::Cause cause) { 692 if (cause == GCCause::_wb_young_gc) { 693 // Young collection for the WhiteBox API. 694 collect(cause, YoungGen); 695 } else { 696 #ifdef ASSERT 697 if (cause == GCCause::_scavenge_alot) { 698 // Young collection only. 699 collect(cause, YoungGen); 700 } else { 701 // Stop-the-world full collection. 702 collect(cause, OldGen); 703 } 704 #else 705 // Stop-the-world full collection. 706 collect(cause, OldGen); 707 #endif 708 } 709 } 710 711 void GenCollectedHeap::collect(GCCause::Cause cause, GenerationType max_generation) { 712 // The caller doesn't have the Heap_lock 713 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock"); 714 MutexLocker ml(Heap_lock); 715 collect_locked(cause, max_generation); 716 } 717 718 void GenCollectedHeap::collect_locked(GCCause::Cause cause) { 719 // The caller has the Heap_lock 720 assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock"); 721 collect_locked(cause, OldGen); 722 } 723 724 // this is the private collection interface 725 // The Heap_lock is expected to be held on entry. 726 727 void GenCollectedHeap::collect_locked(GCCause::Cause cause, GenerationType max_generation) { 728 // Read the GC count while holding the Heap_lock 729 unsigned int gc_count_before = total_collections(); 730 unsigned int full_gc_count_before = total_full_collections(); 731 { 732 MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back 733 VM_GenCollectFull op(gc_count_before, full_gc_count_before, 734 cause, max_generation); 735 VMThread::execute(&op); 736 } 737 } 738 739 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) { 740 do_full_collection(clear_all_soft_refs, OldGen); 741 } 742 743 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs, 744 GenerationType last_generation) { 745 GenerationType local_last_generation; 746 if (!incremental_collection_will_fail(false /* don't consult_young */) && 747 gc_cause() == GCCause::_gc_locker) { 748 local_last_generation = YoungGen; 749 } else { 750 local_last_generation = last_generation; 751 } 752 753 do_collection(true, // full 754 clear_all_soft_refs, // clear_all_soft_refs 755 0, // size 756 false, // is_tlab 757 local_last_generation); // last_generation 758 // Hack XXX FIX ME !!! 759 // A scavenge may not have been attempted, or may have 760 // been attempted and failed, because the old gen was too full 761 if (local_last_generation == YoungGen && gc_cause() == GCCause::_gc_locker && 762 incremental_collection_will_fail(false /* don't consult_young */)) { 763 log_debug(gc, jni)("GC locker: Trying a full collection because scavenge failed"); 764 // This time allow the old gen to be collected as well 765 do_collection(true, // full 766 clear_all_soft_refs, // clear_all_soft_refs 767 0, // size 768 false, // is_tlab 769 OldGen); // last_generation 770 } 771 } 772 773 bool GenCollectedHeap::is_in_young(oop p) { 774 bool result = ((HeapWord*)p) < _old_gen->reserved().start(); 775 assert(result == _young_gen->is_in_reserved(p), 776 "incorrect test - result=%d, p=" INTPTR_FORMAT, result, p2i((void*)p)); 777 return result; 778 } 779 780 // Returns "TRUE" iff "p" points into the committed areas of the heap. 781 bool GenCollectedHeap::is_in(const void* p) const { 782 return _young_gen->is_in(p) || _old_gen->is_in(p); 783 } 784 785 #ifdef ASSERT 786 // Don't implement this by using is_in_young(). This method is used 787 // in some cases to check that is_in_young() is correct. 788 bool GenCollectedHeap::is_in_partial_collection(const void* p) { 789 assert(is_in_reserved(p) || p == NULL, 790 "Does not work if address is non-null and outside of the heap"); 791 return p < _young_gen->reserved().end() && p != NULL; 792 } 793 #endif 794 795 void GenCollectedHeap::oop_iterate_no_header(OopClosure* cl) { 796 NoHeaderExtendedOopClosure no_header_cl(cl); 797 oop_iterate(&no_header_cl); 798 } 799 800 void GenCollectedHeap::oop_iterate(ExtendedOopClosure* cl) { 801 _young_gen->oop_iterate(cl); 802 _old_gen->oop_iterate(cl); 803 } 804 805 void GenCollectedHeap::object_iterate(ObjectClosure* cl) { 806 _young_gen->object_iterate(cl); 807 _old_gen->object_iterate(cl); 808 } 809 810 void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) { 811 _young_gen->safe_object_iterate(cl); 812 _old_gen->safe_object_iterate(cl); 813 } 814 815 Space* GenCollectedHeap::space_containing(const void* addr) const { 816 Space* res = _young_gen->space_containing(addr); 817 if (res != NULL) { 818 return res; 819 } 820 res = _old_gen->space_containing(addr); 821 assert(res != NULL, "Could not find containing space"); 822 return res; 823 } 824 825 HeapWord* GenCollectedHeap::block_start(const void* addr) const { 826 assert(is_in_reserved(addr), "block_start of address outside of heap"); 827 if (_young_gen->is_in_reserved(addr)) { 828 assert(_young_gen->is_in(addr), "addr should be in allocated part of generation"); 829 return _young_gen->block_start(addr); 830 } 831 832 assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address"); 833 assert(_old_gen->is_in(addr), "addr should be in allocated part of generation"); 834 return _old_gen->block_start(addr); 835 } 836 837 size_t GenCollectedHeap::block_size(const HeapWord* addr) const { 838 assert(is_in_reserved(addr), "block_size of address outside of heap"); 839 if (_young_gen->is_in_reserved(addr)) { 840 assert(_young_gen->is_in(addr), "addr should be in allocated part of generation"); 841 return _young_gen->block_size(addr); 842 } 843 844 assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address"); 845 assert(_old_gen->is_in(addr), "addr should be in allocated part of generation"); 846 return _old_gen->block_size(addr); 847 } 848 849 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const { 850 assert(is_in_reserved(addr), "block_is_obj of address outside of heap"); 851 assert(block_start(addr) == addr, "addr must be a block start"); 852 if (_young_gen->is_in_reserved(addr)) { 853 return _young_gen->block_is_obj(addr); 854 } 855 856 assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address"); 857 return _old_gen->block_is_obj(addr); 858 } 859 860 bool GenCollectedHeap::supports_tlab_allocation() const { 861 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!"); 862 return _young_gen->supports_tlab_allocation(); 863 } 864 865 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const { 866 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!"); 867 if (_young_gen->supports_tlab_allocation()) { 868 return _young_gen->tlab_capacity(); 869 } 870 return 0; 871 } 872 873 size_t GenCollectedHeap::tlab_used(Thread* thr) const { 874 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!"); 875 if (_young_gen->supports_tlab_allocation()) { 876 return _young_gen->tlab_used(); 877 } 878 return 0; 879 } 880 881 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const { 882 assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!"); 883 if (_young_gen->supports_tlab_allocation()) { 884 return _young_gen->unsafe_max_tlab_alloc(); 885 } 886 return 0; 887 } 888 889 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t size) { 890 bool gc_overhead_limit_was_exceeded; 891 return gen_policy()->mem_allocate_work(size /* size */, 892 true /* is_tlab */, 893 &gc_overhead_limit_was_exceeded); 894 } 895 896 // Requires "*prev_ptr" to be non-NULL. Deletes and a block of minimal size 897 // from the list headed by "*prev_ptr". 898 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) { 899 bool first = true; 900 size_t min_size = 0; // "first" makes this conceptually infinite. 901 ScratchBlock **smallest_ptr, *smallest; 902 ScratchBlock *cur = *prev_ptr; 903 while (cur) { 904 assert(*prev_ptr == cur, "just checking"); 905 if (first || cur->num_words < min_size) { 906 smallest_ptr = prev_ptr; 907 smallest = cur; 908 min_size = smallest->num_words; 909 first = false; 910 } 911 prev_ptr = &cur->next; 912 cur = cur->next; 913 } 914 smallest = *smallest_ptr; 915 *smallest_ptr = smallest->next; 916 return smallest; 917 } 918 919 // Sort the scratch block list headed by res into decreasing size order, 920 // and set "res" to the result. 921 static void sort_scratch_list(ScratchBlock*& list) { 922 ScratchBlock* sorted = NULL; 923 ScratchBlock* unsorted = list; 924 while (unsorted) { 925 ScratchBlock *smallest = removeSmallestScratch(&unsorted); 926 smallest->next = sorted; 927 sorted = smallest; 928 } 929 list = sorted; 930 } 931 932 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor, 933 size_t max_alloc_words) { 934 ScratchBlock* res = NULL; 935 _young_gen->contribute_scratch(res, requestor, max_alloc_words); 936 _old_gen->contribute_scratch(res, requestor, max_alloc_words); 937 sort_scratch_list(res); 938 return res; 939 } 940 941 void GenCollectedHeap::release_scratch() { 942 _young_gen->reset_scratch(); 943 _old_gen->reset_scratch(); 944 } 945 946 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure { 947 void do_generation(Generation* gen) { 948 gen->prepare_for_verify(); 949 } 950 }; 951 952 void GenCollectedHeap::prepare_for_verify() { 953 ensure_parsability(false); // no need to retire TLABs 954 GenPrepareForVerifyClosure blk; 955 generation_iterate(&blk, false); 956 } 957 958 void GenCollectedHeap::generation_iterate(GenClosure* cl, 959 bool old_to_young) { 960 if (old_to_young) { 961 cl->do_generation(_old_gen); 962 cl->do_generation(_young_gen); 963 } else { 964 cl->do_generation(_young_gen); 965 cl->do_generation(_old_gen); 966 } 967 } 968 969 bool GenCollectedHeap::is_maximal_no_gc() const { 970 return _young_gen->is_maximal_no_gc() && _old_gen->is_maximal_no_gc(); 971 } 972 973 void GenCollectedHeap::save_marks() { 974 _young_gen->save_marks(); 975 _old_gen->save_marks(); 976 } 977 978 GenCollectedHeap* GenCollectedHeap::heap() { 979 CollectedHeap* heap = Universe::heap(); 980 assert(heap != NULL, "Uninitialized access to GenCollectedHeap::heap()"); 981 assert(heap->kind() == CollectedHeap::SerialHeap || 982 heap->kind() == CollectedHeap::CMSHeap, "Not a GenCollectedHeap"); 983 return (GenCollectedHeap*) heap; 984 } 985 986 void GenCollectedHeap::prepare_for_compaction() { 987 // Start by compacting into same gen. 988 CompactPoint cp(_old_gen); 989 _old_gen->prepare_for_compaction(&cp); 990 _young_gen->prepare_for_compaction(&cp); 991 } 992 993 void GenCollectedHeap::verify(VerifyOption option /* ignored */) { 994 log_debug(gc, verify)("%s", _old_gen->name()); 995 _old_gen->verify(); 996 997 log_debug(gc, verify)("%s", _old_gen->name()); 998 _young_gen->verify(); 999 1000 log_debug(gc, verify)("RemSet"); 1001 rem_set()->verify(); 1002 } 1003 1004 void GenCollectedHeap::print_on(outputStream* st) const { 1005 _young_gen->print_on(st); 1006 _old_gen->print_on(st); 1007 MetaspaceAux::print_on(st); 1008 } 1009 1010 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const { 1011 } 1012 1013 void GenCollectedHeap::print_gc_threads_on(outputStream* st) const { 1014 } 1015 1016 void GenCollectedHeap::print_tracing_info() const { 1017 if (log_is_enabled(Debug, gc, heap, exit)) { 1018 LogStreamHandle(Debug, gc, heap, exit) lsh; 1019 _young_gen->print_summary_info_on(&lsh); 1020 _old_gen->print_summary_info_on(&lsh); 1021 } 1022 } 1023 1024 void GenCollectedHeap::print_heap_change(size_t young_prev_used, size_t old_prev_used) const { 1025 log_info(gc, heap)("%s: " SIZE_FORMAT "K->" SIZE_FORMAT "K(" SIZE_FORMAT "K)", 1026 _young_gen->short_name(), young_prev_used / K, _young_gen->used() /K, _young_gen->capacity() /K); 1027 log_info(gc, heap)("%s: " SIZE_FORMAT "K->" SIZE_FORMAT "K(" SIZE_FORMAT "K)", 1028 _old_gen->short_name(), old_prev_used / K, _old_gen->used() /K, _old_gen->capacity() /K); 1029 } 1030 1031 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure { 1032 private: 1033 bool _full; 1034 public: 1035 void do_generation(Generation* gen) { 1036 gen->gc_prologue(_full); 1037 } 1038 GenGCPrologueClosure(bool full) : _full(full) {}; 1039 }; 1040 1041 void GenCollectedHeap::gc_prologue(bool full) { 1042 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer"); 1043 1044 // Fill TLAB's and such 1045 CollectedHeap::accumulate_statistics_all_tlabs(); 1046 ensure_parsability(true); // retire TLABs 1047 1048 // Walk generations 1049 GenGCPrologueClosure blk(full); 1050 generation_iterate(&blk, false); // not old-to-young. 1051 }; 1052 1053 class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure { 1054 private: 1055 bool _full; 1056 public: 1057 void do_generation(Generation* gen) { 1058 gen->gc_epilogue(_full); 1059 } 1060 GenGCEpilogueClosure(bool full) : _full(full) {}; 1061 }; 1062 1063 void GenCollectedHeap::gc_epilogue(bool full) { 1064 #if COMPILER2_OR_JVMCI 1065 assert(DerivedPointerTable::is_empty(), "derived pointer present"); 1066 size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr())); 1067 guarantee(is_client_compilation_mode_vm() || actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps"); 1068 #endif // COMPILER2_OR_JVMCI 1069 1070 resize_all_tlabs(); 1071 1072 GenGCEpilogueClosure blk(full); 1073 generation_iterate(&blk, false); // not old-to-young. 1074 1075 if (!CleanChunkPoolAsync) { 1076 Chunk::clean_chunk_pool(); 1077 } 1078 1079 MetaspaceCounters::update_performance_counters(); 1080 CompressedClassSpaceCounters::update_performance_counters(); 1081 }; 1082 1083 #ifndef PRODUCT 1084 class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure { 1085 private: 1086 public: 1087 void do_generation(Generation* gen) { 1088 gen->record_spaces_top(); 1089 } 1090 }; 1091 1092 void GenCollectedHeap::record_gen_tops_before_GC() { 1093 if (ZapUnusedHeapArea) { 1094 GenGCSaveTopsBeforeGCClosure blk; 1095 generation_iterate(&blk, false); // not old-to-young. 1096 } 1097 } 1098 #endif // not PRODUCT 1099 1100 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure { 1101 public: 1102 void do_generation(Generation* gen) { 1103 gen->ensure_parsability(); 1104 } 1105 }; 1106 1107 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) { 1108 CollectedHeap::ensure_parsability(retire_tlabs); 1109 GenEnsureParsabilityClosure ep_cl; 1110 generation_iterate(&ep_cl, false); 1111 } 1112 1113 oop GenCollectedHeap::handle_failed_promotion(Generation* old_gen, 1114 oop obj, 1115 size_t obj_size) { 1116 guarantee(old_gen == _old_gen, "We only get here with an old generation"); 1117 assert(obj_size == (size_t)obj->size(), "bad obj_size passed in"); 1118 HeapWord* result = NULL; 1119 1120 result = old_gen->expand_and_allocate(obj_size, false); 1121 1122 if (result != NULL) { 1123 Copy::aligned_disjoint_words((HeapWord*)obj, result, obj_size); 1124 } 1125 return oop(result); 1126 } 1127 1128 class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure { 1129 jlong _time; // in ms 1130 jlong _now; // in ms 1131 1132 public: 1133 GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { } 1134 1135 jlong time() { return _time; } 1136 1137 void do_generation(Generation* gen) { 1138 _time = MIN2(_time, gen->time_of_last_gc(_now)); 1139 } 1140 }; 1141 1142 jlong GenCollectedHeap::millis_since_last_gc() { 1143 // javaTimeNanos() is guaranteed to be monotonically non-decreasing 1144 // provided the underlying platform provides such a time source 1145 // (and it is bug free). So we still have to guard against getting 1146 // back a time later than 'now'. 1147 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC; 1148 GenTimeOfLastGCClosure tolgc_cl(now); 1149 // iterate over generations getting the oldest 1150 // time that a generation was collected 1151 generation_iterate(&tolgc_cl, false); 1152 1153 jlong retVal = now - tolgc_cl.time(); 1154 if (retVal < 0) { 1155 log_warning(gc)("millis_since_last_gc() would return : " JLONG_FORMAT 1156 ". returning zero instead.", retVal); 1157 return 0; 1158 } 1159 return retVal; 1160 }