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