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