1 /* 2 * Copyright (c) 2002, 2019, 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/classLoaderDataGraph.hpp" 28 #include "classfile/stringTable.hpp" 29 #include "code/codeCache.hpp" 30 #include "gc/parallel/parallelScavengeHeap.hpp" 31 #include "gc/parallel/psAdaptiveSizePolicy.hpp" 32 #include "gc/parallel/psClosure.inline.hpp" 33 #include "gc/parallel/psCompactionManager.hpp" 34 #include "gc/parallel/psMarkSweepProxy.hpp" 35 #include "gc/parallel/psParallelCompact.inline.hpp" 36 #include "gc/parallel/psPromotionManager.inline.hpp" 37 #include "gc/parallel/psRootType.hpp" 38 #include "gc/parallel/psScavenge.inline.hpp" 39 #include "gc/shared/gcCause.hpp" 40 #include "gc/shared/gcHeapSummary.hpp" 41 #include "gc/shared/gcId.hpp" 42 #include "gc/shared/gcLocker.hpp" 43 #include "gc/shared/gcTimer.hpp" 44 #include "gc/shared/gcTrace.hpp" 45 #include "gc/shared/gcTraceTime.inline.hpp" 46 #include "gc/shared/isGCActiveMark.hpp" 47 #include "gc/shared/referencePolicy.hpp" 48 #include "gc/shared/referenceProcessor.hpp" 49 #include "gc/shared/referenceProcessorPhaseTimes.hpp" 50 #include "gc/shared/scavengableNMethods.hpp" 51 #include "gc/shared/spaceDecorator.inline.hpp" 52 #include "gc/shared/weakProcessor.hpp" 53 #include "gc/shared/workerPolicy.hpp" 54 #include "gc/shared/workgroup.hpp" 55 #include "memory/iterator.hpp" 56 #include "memory/resourceArea.hpp" 57 #include "memory/universe.hpp" 58 #include "logging/log.hpp" 59 #include "oops/access.inline.hpp" 60 #include "oops/compressedOops.inline.hpp" 61 #include "oops/oop.inline.hpp" 62 #include "runtime/biasedLocking.hpp" 63 #include "runtime/handles.inline.hpp" 64 #include "runtime/threadCritical.hpp" 65 #include "runtime/vmThread.hpp" 66 #include "runtime/vmOperations.hpp" 67 #include "services/management.hpp" 68 #include "services/memoryService.hpp" 69 #include "utilities/stack.inline.hpp" 70 71 HeapWord* PSScavenge::_to_space_top_before_gc = NULL; 72 int PSScavenge::_consecutive_skipped_scavenges = 0; 73 SpanSubjectToDiscoveryClosure PSScavenge::_span_based_discoverer; 74 ReferenceProcessor* PSScavenge::_ref_processor = NULL; 75 PSCardTable* PSScavenge::_card_table = NULL; 76 bool PSScavenge::_survivor_overflow = false; 77 uint PSScavenge::_tenuring_threshold = 0; 78 HeapWord* PSScavenge::_young_generation_boundary = NULL; 79 uintptr_t PSScavenge::_young_generation_boundary_compressed = 0; 80 elapsedTimer PSScavenge::_accumulated_time; 81 STWGCTimer PSScavenge::_gc_timer; 82 ParallelScavengeTracer PSScavenge::_gc_tracer; 83 CollectorCounters* PSScavenge::_counters = NULL; 84 85 static void scavenge_roots_work(ParallelRootType::Value root_type, uint worker_id) { 86 assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc"); 87 88 PSPromotionManager* pm = PSPromotionManager::gc_thread_promotion_manager(worker_id); 89 PSScavengeRootsClosure roots_closure(pm); 90 PSPromoteRootsClosure roots_to_old_closure(pm); 91 92 switch (root_type) { 93 case ParallelRootType::universe: 94 Universe::oops_do(&roots_closure); 95 break; 96 97 case ParallelRootType::jni_handles: 98 JNIHandles::oops_do(&roots_closure); 99 break; 100 101 case ParallelRootType::object_synchronizer: 102 ObjectSynchronizer::oops_do(&roots_closure); 103 break; 104 105 case ParallelRootType::system_dictionary: 106 SystemDictionary::oops_do(&roots_closure); 107 break; 108 109 case ParallelRootType::class_loader_data: 110 { 111 PSScavengeCLDClosure cld_closure(pm); 112 ClassLoaderDataGraph::cld_do(&cld_closure); 113 } 114 break; 115 116 case ParallelRootType::management: 117 Management::oops_do(&roots_closure); 118 break; 119 120 case ParallelRootType::jvmti: 121 JvmtiExport::oops_do(&roots_closure); 122 break; 123 124 case ParallelRootType::code_cache: 125 { 126 MarkingCodeBlobClosure code_closure(&roots_to_old_closure, CodeBlobToOopClosure::FixRelocations); 127 ScavengableNMethods::nmethods_do(&code_closure); 128 AOTLoader::oops_do(&roots_closure); 129 } 130 break; 131 132 case ParallelRootType::sentinel: 133 DEBUG_ONLY(default:) // DEBUG_ONLY hack will create compile error on release builds (-Wswitch) and runtime check on debug builds 134 fatal("Bad enumeration value: %u", root_type); 135 break; 136 } 137 138 // Do the real work 139 pm->drain_stacks(false); 140 } 141 142 static void steal_work(ParallelTaskTerminator& terminator, uint worker_id) { 143 assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc"); 144 145 PSPromotionManager* pm = 146 PSPromotionManager::gc_thread_promotion_manager(worker_id); 147 pm->drain_stacks(true); 148 guarantee(pm->stacks_empty(), 149 "stacks should be empty at this point"); 150 151 while (true) { 152 StarTask p; 153 if (PSPromotionManager::steal_depth(worker_id, p)) { 154 TASKQUEUE_STATS_ONLY(pm->record_steal(p)); 155 pm->process_popped_location_depth(p); 156 pm->drain_stacks_depth(true); 157 } else { 158 if (terminator.offer_termination()) { 159 break; 160 } 161 } 162 } 163 guarantee(pm->stacks_empty(), "stacks should be empty at this point"); 164 } 165 166 // Define before use 167 class PSIsAliveClosure: public BoolObjectClosure { 168 public: 169 bool do_object_b(oop p) { 170 return (!PSScavenge::is_obj_in_young(p)) || p->is_forwarded(); 171 } 172 }; 173 174 PSIsAliveClosure PSScavenge::_is_alive_closure; 175 176 class PSKeepAliveClosure: public OopClosure { 177 protected: 178 MutableSpace* _to_space; 179 PSPromotionManager* _promotion_manager; 180 181 public: 182 PSKeepAliveClosure(PSPromotionManager* pm) : _promotion_manager(pm) { 183 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap(); 184 _to_space = heap->young_gen()->to_space(); 185 186 assert(_promotion_manager != NULL, "Sanity"); 187 } 188 189 template <class T> void do_oop_work(T* p) { 190 assert (oopDesc::is_oop(RawAccess<IS_NOT_NULL>::oop_load(p)), 191 "expected an oop while scanning weak refs"); 192 193 // Weak refs may be visited more than once. 194 if (PSScavenge::should_scavenge(p, _to_space)) { 195 _promotion_manager->copy_and_push_safe_barrier<T, /*promote_immediately=*/false>(p); 196 } 197 } 198 virtual void do_oop(oop* p) { PSKeepAliveClosure::do_oop_work(p); } 199 virtual void do_oop(narrowOop* p) { PSKeepAliveClosure::do_oop_work(p); } 200 }; 201 202 class PSEvacuateFollowersClosure: public VoidClosure { 203 private: 204 PSPromotionManager* _promotion_manager; 205 public: 206 PSEvacuateFollowersClosure(PSPromotionManager* pm) : _promotion_manager(pm) {} 207 208 virtual void do_void() { 209 assert(_promotion_manager != NULL, "Sanity"); 210 _promotion_manager->drain_stacks(true); 211 guarantee(_promotion_manager->stacks_empty(), 212 "stacks should be empty at this point"); 213 } 214 }; 215 216 class PSRefProcTaskExecutor: public AbstractRefProcTaskExecutor { 217 virtual void execute(ProcessTask& process_task, uint ergo_workers); 218 }; 219 220 class PSRefProcTask : public AbstractGangTask { 221 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask; 222 TaskTerminator _terminator; 223 ProcessTask& _task; 224 uint _active_workers; 225 226 public: 227 PSRefProcTask(ProcessTask& task, uint active_workers) 228 : AbstractGangTask("PSRefProcTask"), 229 _terminator(active_workers, PSPromotionManager::stack_array_depth()), 230 _task(task), 231 _active_workers(active_workers) { 232 } 233 234 virtual void work(uint worker_id) { 235 PSPromotionManager* promotion_manager = 236 PSPromotionManager::gc_thread_promotion_manager(worker_id); 237 assert(promotion_manager != NULL, "sanity check"); 238 PSKeepAliveClosure keep_alive(promotion_manager); 239 PSEvacuateFollowersClosure evac_followers(promotion_manager); 240 PSIsAliveClosure is_alive; 241 _task.work(worker_id, is_alive, keep_alive, evac_followers); 242 243 if (_task.marks_oops_alive() && _active_workers > 1) { 244 steal_work(*_terminator.terminator(), worker_id); 245 } 246 } 247 }; 248 249 void PSRefProcTaskExecutor::execute(ProcessTask& process_task, uint ergo_workers) { 250 PSRefProcTask task(process_task, ergo_workers); 251 ParallelScavengeHeap::heap()->workers().run_task(&task); 252 } 253 254 // This method contains all heap specific policy for invoking scavenge. 255 // PSScavenge::invoke_no_policy() will do nothing but attempt to 256 // scavenge. It will not clean up after failed promotions, bail out if 257 // we've exceeded policy time limits, or any other special behavior. 258 // All such policy should be placed here. 259 // 260 // Note that this method should only be called from the vm_thread while 261 // at a safepoint! 262 bool PSScavenge::invoke() { 263 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); 264 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); 265 assert(!ParallelScavengeHeap::heap()->is_gc_active(), "not reentrant"); 266 267 ParallelScavengeHeap* const heap = ParallelScavengeHeap::heap(); 268 PSAdaptiveSizePolicy* policy = heap->size_policy(); 269 IsGCActiveMark mark; 270 271 const bool scavenge_done = PSScavenge::invoke_no_policy(); 272 const bool need_full_gc = !scavenge_done || 273 policy->should_full_GC(heap->old_gen()->free_in_bytes()); 274 bool full_gc_done = false; 275 276 if (UsePerfData) { 277 PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters(); 278 const int ffs_val = need_full_gc ? full_follows_scavenge : not_skipped; 279 counters->update_full_follows_scavenge(ffs_val); 280 } 281 282 if (need_full_gc) { 283 GCCauseSetter gccs(heap, GCCause::_adaptive_size_policy); 284 SoftRefPolicy* srp = heap->soft_ref_policy(); 285 const bool clear_all_softrefs = srp->should_clear_all_soft_refs(); 286 287 if (UseParallelOldGC) { 288 full_gc_done = PSParallelCompact::invoke_no_policy(clear_all_softrefs); 289 } else { 290 full_gc_done = PSMarkSweepProxy::invoke_no_policy(clear_all_softrefs); 291 } 292 } 293 294 return full_gc_done; 295 } 296 297 class PSThreadRootsTaskClosure : public ThreadClosure { 298 uint _worker_id; 299 public: 300 PSThreadRootsTaskClosure(uint worker_id) : _worker_id(worker_id) { } 301 virtual void do_thread(Thread* thread) { 302 assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc"); 303 304 PSPromotionManager* pm = PSPromotionManager::gc_thread_promotion_manager(_worker_id); 305 PSScavengeRootsClosure roots_closure(pm); 306 MarkingCodeBlobClosure roots_in_blobs(&roots_closure, CodeBlobToOopClosure::FixRelocations); 307 308 thread->oops_do(&roots_closure, &roots_in_blobs); 309 310 // Do the real work 311 pm->drain_stacks(false); 312 } 313 }; 314 315 class ScavengeRootsTask : public AbstractGangTask { 316 StrongRootsScope _strong_roots_scope; // needed for Threads::possibly_parallel_threads_do 317 SequentialSubTasksDone _subtasks; 318 PSOldGen* _old_gen; 319 HeapWord* _gen_top; 320 uint _active_workers; 321 bool _is_empty; 322 TaskTerminator _terminator; 323 324 public: 325 ScavengeRootsTask(PSOldGen* old_gen, 326 HeapWord* gen_top, 327 uint active_workers, 328 bool is_empty) : 329 AbstractGangTask("ScavengeRootsTask"), 330 _strong_roots_scope(active_workers), 331 _subtasks(), 332 _old_gen(old_gen), 333 _gen_top(gen_top), 334 _active_workers(active_workers), 335 _is_empty(is_empty), 336 _terminator(active_workers, PSPromotionManager::vm_thread_promotion_manager()->stack_array_depth()) { 337 _subtasks.set_n_threads(active_workers); 338 _subtasks.set_n_tasks(ParallelRootType::sentinel); 339 } 340 341 virtual void work(uint worker_id) { 342 ResourceMark rm; 343 344 if (!_is_empty) { 345 // There are only old-to-young pointers if there are objects 346 // in the old gen. 347 348 assert(_old_gen != NULL, "Sanity"); 349 // There are no old-to-young pointers if the old gen is empty. 350 assert(!_old_gen->object_space()->is_empty(), "Should not be called is there is no work"); 351 assert(_old_gen->object_space()->contains(_gen_top) || _gen_top == _old_gen->object_space()->top(), "Sanity"); 352 assert(worker_id < ParallelGCThreads, "Sanity"); 353 354 { 355 PSPromotionManager* pm = PSPromotionManager::gc_thread_promotion_manager(worker_id); 356 PSCardTable* card_table = ParallelScavengeHeap::heap()->card_table(); 357 358 card_table->scavenge_contents_parallel(_old_gen->start_array(), 359 _old_gen->object_space(), 360 _gen_top, 361 pm, 362 worker_id, 363 _active_workers); 364 365 // Do the real work 366 pm->drain_stacks(false); 367 } 368 } 369 370 for (uint root_type = 0; _subtasks.try_claim_task(root_type); /* empty */ ) { 371 scavenge_roots_work(static_cast<ParallelRootType::Value>(root_type), worker_id); 372 } 373 _subtasks.all_tasks_completed(); 374 375 PSThreadRootsTaskClosure closure(worker_id); 376 Threads::possibly_parallel_threads_do(true /*parallel */, &closure); 377 378 379 // If active_workers can exceed 1, add a steal_work(). 380 // PSPromotionManager::drain_stacks_depth() does not fully drain its 381 // stacks and expects a steal_work() to complete the draining if 382 // ParallelGCThreads is > 1. 383 384 if (_active_workers > 1) { 385 steal_work(*_terminator.terminator() , worker_id); 386 } 387 } 388 }; 389 390 // This method contains no policy. You should probably 391 // be calling invoke() instead. 392 bool PSScavenge::invoke_no_policy() { 393 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); 394 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); 395 396 _gc_timer.register_gc_start(); 397 398 TimeStamp scavenge_entry; 399 TimeStamp scavenge_midpoint; 400 TimeStamp scavenge_exit; 401 402 scavenge_entry.update(); 403 404 if (GCLocker::check_active_before_gc()) { 405 return false; 406 } 407 408 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap(); 409 GCCause::Cause gc_cause = heap->gc_cause(); 410 411 // Check for potential problems. 412 if (!should_attempt_scavenge()) { 413 return false; 414 } 415 416 GCIdMark gc_id_mark; 417 _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start()); 418 419 bool promotion_failure_occurred = false; 420 421 PSYoungGen* young_gen = heap->young_gen(); 422 PSOldGen* old_gen = heap->old_gen(); 423 PSAdaptiveSizePolicy* size_policy = heap->size_policy(); 424 425 heap->increment_total_collections(); 426 427 if (AdaptiveSizePolicy::should_update_eden_stats(gc_cause)) { 428 // Gather the feedback data for eden occupancy. 429 young_gen->eden_space()->accumulate_statistics(); 430 } 431 432 heap->print_heap_before_gc(); 433 heap->trace_heap_before_gc(&_gc_tracer); 434 435 assert(!NeverTenure || _tenuring_threshold == markWord::max_age + 1, "Sanity"); 436 assert(!AlwaysTenure || _tenuring_threshold == 0, "Sanity"); 437 438 // Fill in TLABs 439 heap->ensure_parsability(true); // retire TLABs 440 441 if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) { 442 HandleMark hm; // Discard invalid handles created during verification 443 Universe::verify("Before GC"); 444 } 445 446 { 447 ResourceMark rm; 448 HandleMark hm; 449 450 GCTraceCPUTime tcpu; 451 GCTraceTime(Info, gc) tm("Pause Young", NULL, gc_cause, true); 452 TraceCollectorStats tcs(counters()); 453 TraceMemoryManagerStats tms(heap->young_gc_manager(), gc_cause); 454 455 if (log_is_enabled(Debug, gc, heap, exit)) { 456 accumulated_time()->start(); 457 } 458 459 // Let the size policy know we're starting 460 size_policy->minor_collection_begin(); 461 462 // Verify the object start arrays. 463 if (VerifyObjectStartArray && 464 VerifyBeforeGC) { 465 old_gen->verify_object_start_array(); 466 } 467 468 // Verify no unmarked old->young roots 469 if (VerifyRememberedSets) { 470 heap->card_table()->verify_all_young_refs_imprecise(); 471 } 472 473 assert(young_gen->to_space()->is_empty(), 474 "Attempt to scavenge with live objects in to_space"); 475 young_gen->to_space()->clear(SpaceDecorator::Mangle); 476 477 save_to_space_top_before_gc(); 478 479 #if COMPILER2_OR_JVMCI 480 DerivedPointerTable::clear(); 481 #endif 482 483 reference_processor()->enable_discovery(); 484 reference_processor()->setup_policy(false); 485 486 const PreGenGCValues pre_gc_values = heap->get_pre_gc_values(); 487 488 // Reset our survivor overflow. 489 set_survivor_overflow(false); 490 491 // We need to save the old top values before 492 // creating the promotion_manager. We pass the top 493 // values to the card_table, to prevent it from 494 // straying into the promotion labs. 495 HeapWord* old_top = old_gen->object_space()->top(); 496 497 const uint active_workers = 498 WorkerPolicy::calc_active_workers(ParallelScavengeHeap::heap()->workers().total_workers(), 499 ParallelScavengeHeap::heap()->workers().active_workers(), 500 Threads::number_of_non_daemon_threads()); 501 ParallelScavengeHeap::heap()->workers().update_active_workers(active_workers); 502 503 PSPromotionManager::pre_scavenge(); 504 505 // We'll use the promotion manager again later. 506 PSPromotionManager* promotion_manager = PSPromotionManager::vm_thread_promotion_manager(); 507 { 508 GCTraceTime(Debug, gc, phases) tm("Scavenge", &_gc_timer); 509 510 ScavengeRootsTask task(old_gen, old_top, active_workers, old_gen->object_space()->is_empty()); 511 ParallelScavengeHeap::heap()->workers().run_task(&task); 512 } 513 514 scavenge_midpoint.update(); 515 516 // Process reference objects discovered during scavenge 517 { 518 GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer); 519 520 reference_processor()->setup_policy(false); // not always_clear 521 reference_processor()->set_active_mt_degree(active_workers); 522 PSKeepAliveClosure keep_alive(promotion_manager); 523 PSEvacuateFollowersClosure evac_followers(promotion_manager); 524 ReferenceProcessorStats stats; 525 ReferenceProcessorPhaseTimes pt(&_gc_timer, reference_processor()->max_num_queues()); 526 if (reference_processor()->processing_is_mt()) { 527 PSRefProcTaskExecutor task_executor; 528 stats = reference_processor()->process_discovered_references( 529 &_is_alive_closure, &keep_alive, &evac_followers, &task_executor, 530 &pt); 531 } else { 532 stats = reference_processor()->process_discovered_references( 533 &_is_alive_closure, &keep_alive, &evac_followers, NULL, &pt); 534 } 535 536 _gc_tracer.report_gc_reference_stats(stats); 537 pt.print_all_references(); 538 } 539 540 assert(promotion_manager->stacks_empty(),"stacks should be empty at this point"); 541 542 PSScavengeRootsClosure root_closure(promotion_manager); 543 544 { 545 GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer); 546 WeakProcessor::weak_oops_do(&_is_alive_closure, &root_closure); 547 } 548 549 // Verify that usage of root_closure didn't copy any objects. 550 assert(promotion_manager->stacks_empty(),"stacks should be empty at this point"); 551 552 // Finally, flush the promotion_manager's labs, and deallocate its stacks. 553 promotion_failure_occurred = PSPromotionManager::post_scavenge(_gc_tracer); 554 if (promotion_failure_occurred) { 555 clean_up_failed_promotion(); 556 log_info(gc, promotion)("Promotion failed"); 557 } 558 559 _gc_tracer.report_tenuring_threshold(tenuring_threshold()); 560 561 // Let the size policy know we're done. Note that we count promotion 562 // failure cleanup time as part of the collection (otherwise, we're 563 // implicitly saying it's mutator time). 564 size_policy->minor_collection_end(gc_cause); 565 566 if (!promotion_failure_occurred) { 567 // Swap the survivor spaces. 568 young_gen->eden_space()->clear(SpaceDecorator::Mangle); 569 young_gen->from_space()->clear(SpaceDecorator::Mangle); 570 young_gen->swap_spaces(); 571 572 size_t survived = young_gen->from_space()->used_in_bytes(); 573 size_t promoted = old_gen->used_in_bytes() - pre_gc_values.old_gen_used(); 574 size_policy->update_averages(_survivor_overflow, survived, promoted); 575 576 // A successful scavenge should restart the GC time limit count which is 577 // for full GC's. 578 size_policy->reset_gc_overhead_limit_count(); 579 if (UseAdaptiveSizePolicy) { 580 // Calculate the new survivor size and tenuring threshold 581 582 log_debug(gc, ergo)("AdaptiveSizeStart: collection: %d ", heap->total_collections()); 583 log_trace(gc, ergo)("old_gen_capacity: " SIZE_FORMAT " young_gen_capacity: " SIZE_FORMAT, 584 old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes()); 585 586 if (UsePerfData) { 587 PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters(); 588 counters->update_old_eden_size( 589 size_policy->calculated_eden_size_in_bytes()); 590 counters->update_old_promo_size( 591 size_policy->calculated_promo_size_in_bytes()); 592 counters->update_old_capacity(old_gen->capacity_in_bytes()); 593 counters->update_young_capacity(young_gen->capacity_in_bytes()); 594 counters->update_survived(survived); 595 counters->update_promoted(promoted); 596 counters->update_survivor_overflowed(_survivor_overflow); 597 } 598 599 size_t max_young_size = young_gen->max_size(); 600 601 // Deciding a free ratio in the young generation is tricky, so if 602 // MinHeapFreeRatio or MaxHeapFreeRatio are in use (implicating 603 // that the old generation size may have been limited because of them) we 604 // should then limit our young generation size using NewRatio to have it 605 // follow the old generation size. 606 if (MinHeapFreeRatio != 0 || MaxHeapFreeRatio != 100) { 607 max_young_size = MIN2(old_gen->capacity_in_bytes() / NewRatio, young_gen->max_size()); 608 } 609 610 size_t survivor_limit = 611 size_policy->max_survivor_size(max_young_size); 612 _tenuring_threshold = 613 size_policy->compute_survivor_space_size_and_threshold( 614 _survivor_overflow, 615 _tenuring_threshold, 616 survivor_limit); 617 618 log_debug(gc, age)("Desired survivor size " SIZE_FORMAT " bytes, new threshold %u (max threshold " UINTX_FORMAT ")", 619 size_policy->calculated_survivor_size_in_bytes(), 620 _tenuring_threshold, MaxTenuringThreshold); 621 622 if (UsePerfData) { 623 PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters(); 624 counters->update_tenuring_threshold(_tenuring_threshold); 625 counters->update_survivor_size_counters(); 626 } 627 628 // Do call at minor collections? 629 // Don't check if the size_policy is ready at this 630 // level. Let the size_policy check that internally. 631 if (UseAdaptiveGenerationSizePolicyAtMinorCollection && 632 (AdaptiveSizePolicy::should_update_eden_stats(gc_cause))) { 633 // Calculate optimal free space amounts 634 assert(young_gen->max_size() > 635 young_gen->from_space()->capacity_in_bytes() + 636 young_gen->to_space()->capacity_in_bytes(), 637 "Sizes of space in young gen are out-of-bounds"); 638 639 size_t young_live = young_gen->used_in_bytes(); 640 size_t eden_live = young_gen->eden_space()->used_in_bytes(); 641 size_t cur_eden = young_gen->eden_space()->capacity_in_bytes(); 642 size_t max_old_gen_size = old_gen->max_gen_size(); 643 size_t max_eden_size = max_young_size - 644 young_gen->from_space()->capacity_in_bytes() - 645 young_gen->to_space()->capacity_in_bytes(); 646 647 // Used for diagnostics 648 size_policy->clear_generation_free_space_flags(); 649 650 size_policy->compute_eden_space_size(young_live, 651 eden_live, 652 cur_eden, 653 max_eden_size, 654 false /* not full gc*/); 655 656 size_policy->check_gc_overhead_limit(eden_live, 657 max_old_gen_size, 658 max_eden_size, 659 false /* not full gc*/, 660 gc_cause, 661 heap->soft_ref_policy()); 662 663 size_policy->decay_supplemental_growth(false /* not full gc*/); 664 } 665 // Resize the young generation at every collection 666 // even if new sizes have not been calculated. This is 667 // to allow resizes that may have been inhibited by the 668 // relative location of the "to" and "from" spaces. 669 670 // Resizing the old gen at young collections can cause increases 671 // that don't feed back to the generation sizing policy until 672 // a full collection. Don't resize the old gen here. 673 674 heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(), 675 size_policy->calculated_survivor_size_in_bytes()); 676 677 log_debug(gc, ergo)("AdaptiveSizeStop: collection: %d ", heap->total_collections()); 678 } 679 680 // Update the structure of the eden. With NUMA-eden CPU hotplugging or offlining can 681 // cause the change of the heap layout. Make sure eden is reshaped if that's the case. 682 // Also update() will case adaptive NUMA chunk resizing. 683 assert(young_gen->eden_space()->is_empty(), "eden space should be empty now"); 684 young_gen->eden_space()->update(); 685 686 heap->gc_policy_counters()->update_counters(); 687 688 heap->resize_all_tlabs(); 689 690 assert(young_gen->to_space()->is_empty(), "to space should be empty now"); 691 } 692 693 #if COMPILER2_OR_JVMCI 694 DerivedPointerTable::update_pointers(); 695 #endif 696 697 NOT_PRODUCT(reference_processor()->verify_no_references_recorded()); 698 699 // Re-verify object start arrays 700 if (VerifyObjectStartArray && 701 VerifyAfterGC) { 702 old_gen->verify_object_start_array(); 703 } 704 705 // Verify all old -> young cards are now precise 706 if (VerifyRememberedSets) { 707 // Precise verification will give false positives. Until this is fixed, 708 // use imprecise verification. 709 // heap->card_table()->verify_all_young_refs_precise(); 710 heap->card_table()->verify_all_young_refs_imprecise(); 711 } 712 713 if (log_is_enabled(Debug, gc, heap, exit)) { 714 accumulated_time()->stop(); 715 } 716 717 heap->print_heap_change(pre_gc_values); 718 719 // Track memory usage and detect low memory 720 MemoryService::track_memory_usage(); 721 heap->update_counters(); 722 } 723 724 if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) { 725 HandleMark hm; // Discard invalid handles created during verification 726 Universe::verify("After GC"); 727 } 728 729 heap->print_heap_after_gc(); 730 heap->trace_heap_after_gc(&_gc_tracer); 731 732 scavenge_exit.update(); 733 734 log_debug(gc, task, time)("VM-Thread " JLONG_FORMAT " " JLONG_FORMAT " " JLONG_FORMAT, 735 scavenge_entry.ticks(), scavenge_midpoint.ticks(), 736 scavenge_exit.ticks()); 737 738 #ifdef TRACESPINNING 739 ParallelTaskTerminator::print_termination_counts(); 740 #endif 741 742 AdaptiveSizePolicyOutput::print(size_policy, heap->total_collections()); 743 744 _gc_timer.register_gc_end(); 745 746 _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions()); 747 748 return !promotion_failure_occurred; 749 } 750 751 // This method iterates over all objects in the young generation, 752 // removing all forwarding references. It then restores any preserved marks. 753 void PSScavenge::clean_up_failed_promotion() { 754 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap(); 755 PSYoungGen* young_gen = heap->young_gen(); 756 757 RemoveForwardedPointerClosure remove_fwd_ptr_closure; 758 young_gen->object_iterate(&remove_fwd_ptr_closure); 759 760 PSPromotionManager::restore_preserved_marks(); 761 762 // Reset the PromotionFailureALot counters. 763 NOT_PRODUCT(heap->reset_promotion_should_fail();) 764 } 765 766 bool PSScavenge::should_attempt_scavenge() { 767 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap(); 768 PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters(); 769 770 if (UsePerfData) { 771 counters->update_scavenge_skipped(not_skipped); 772 } 773 774 PSYoungGen* young_gen = heap->young_gen(); 775 PSOldGen* old_gen = heap->old_gen(); 776 777 // Do not attempt to promote unless to_space is empty 778 if (!young_gen->to_space()->is_empty()) { 779 _consecutive_skipped_scavenges++; 780 if (UsePerfData) { 781 counters->update_scavenge_skipped(to_space_not_empty); 782 } 783 return false; 784 } 785 786 // Test to see if the scavenge will likely fail. 787 PSAdaptiveSizePolicy* policy = heap->size_policy(); 788 789 // A similar test is done in the policy's should_full_GC(). If this is 790 // changed, decide if that test should also be changed. 791 size_t avg_promoted = (size_t) policy->padded_average_promoted_in_bytes(); 792 size_t promotion_estimate = MIN2(avg_promoted, young_gen->used_in_bytes()); 793 bool result = promotion_estimate < old_gen->free_in_bytes(); 794 795 log_trace(ergo)("%s scavenge: average_promoted " SIZE_FORMAT " padded_average_promoted " SIZE_FORMAT " free in old gen " SIZE_FORMAT, 796 result ? "Do" : "Skip", (size_t) policy->average_promoted_in_bytes(), 797 (size_t) policy->padded_average_promoted_in_bytes(), 798 old_gen->free_in_bytes()); 799 if (young_gen->used_in_bytes() < (size_t) policy->padded_average_promoted_in_bytes()) { 800 log_trace(ergo)(" padded_promoted_average is greater than maximum promotion = " SIZE_FORMAT, young_gen->used_in_bytes()); 801 } 802 803 if (result) { 804 _consecutive_skipped_scavenges = 0; 805 } else { 806 _consecutive_skipped_scavenges++; 807 if (UsePerfData) { 808 counters->update_scavenge_skipped(promoted_too_large); 809 } 810 } 811 return result; 812 } 813 814 // Adaptive size policy support. When the young generation/old generation 815 // boundary moves, _young_generation_boundary must be reset 816 void PSScavenge::set_young_generation_boundary(HeapWord* v) { 817 _young_generation_boundary = v; 818 if (UseCompressedOops) { 819 _young_generation_boundary_compressed = (uintptr_t)CompressedOops::encode((oop)v); 820 } 821 } 822 823 void PSScavenge::initialize() { 824 // Arguments must have been parsed 825 826 if (AlwaysTenure || NeverTenure) { 827 assert(MaxTenuringThreshold == 0 || MaxTenuringThreshold == markWord::max_age + 1, 828 "MaxTenuringThreshold should be 0 or markWord::max_age + 1, but is %d", (int) MaxTenuringThreshold); 829 _tenuring_threshold = MaxTenuringThreshold; 830 } else { 831 // We want to smooth out our startup times for the AdaptiveSizePolicy 832 _tenuring_threshold = (UseAdaptiveSizePolicy) ? InitialTenuringThreshold : 833 MaxTenuringThreshold; 834 } 835 836 ParallelScavengeHeap* heap = ParallelScavengeHeap::heap(); 837 PSYoungGen* young_gen = heap->young_gen(); 838 PSOldGen* old_gen = heap->old_gen(); 839 840 // Set boundary between young_gen and old_gen 841 assert(old_gen->reserved().end() <= young_gen->eden_space()->bottom(), 842 "old above young"); 843 set_young_generation_boundary(young_gen->eden_space()->bottom()); 844 845 // Initialize ref handling object for scavenging. 846 _span_based_discoverer.set_span(young_gen->reserved()); 847 _ref_processor = 848 new ReferenceProcessor(&_span_based_discoverer, 849 ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing 850 ParallelGCThreads, // mt processing degree 851 true, // mt discovery 852 ParallelGCThreads, // mt discovery degree 853 true, // atomic_discovery 854 NULL, // header provides liveness info 855 false); 856 857 // Cache the cardtable 858 _card_table = heap->card_table(); 859 860 _counters = new CollectorCounters("Parallel young collection pauses", 0); 861 }