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