1 /*
   2  * Copyright (c) 2002, 2020, 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/psParallelCompact.inline.hpp"
  35 #include "gc/parallel/psPromotionManager.inline.hpp"
  36 #include "gc/parallel/psRootType.hpp"
  37 #include "gc/parallel/psScavenge.inline.hpp"
  38 #include "gc/shared/gcCause.hpp"
  39 #include "gc/shared/gcHeapSummary.hpp"
  40 #include "gc/shared/gcId.hpp"
  41 #include "gc/shared/gcLocker.hpp"
  42 #include "gc/shared/gcTimer.hpp"
  43 #include "gc/shared/gcTrace.hpp"
  44 #include "gc/shared/gcTraceTime.inline.hpp"
  45 #include "gc/shared/isGCActiveMark.hpp"
  46 #include "gc/shared/referencePolicy.hpp"
  47 #include "gc/shared/referenceProcessor.hpp"
  48 #include "gc/shared/referenceProcessorPhaseTimes.hpp"
  49 #include "gc/shared/scavengableNMethods.hpp"
  50 #include "gc/shared/spaceDecorator.inline.hpp"
  51 #include "gc/shared/taskTerminator.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(TaskTerminator& 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, 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     full_gc_done = PSParallelCompact::invoke_no_policy(clear_all_softrefs);
 288   }
 289 
 290   return full_gc_done;
 291 }
 292 
 293 class PSThreadRootsTaskClosure : public ThreadClosure {
 294   uint _worker_id;
 295 public:
 296   PSThreadRootsTaskClosure(uint worker_id) : _worker_id(worker_id) { }
 297   virtual void do_thread(Thread* thread) {
 298     assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
 299 
 300     PSPromotionManager* pm = PSPromotionManager::gc_thread_promotion_manager(_worker_id);
 301     PSScavengeRootsClosure roots_closure(pm);
 302     MarkingCodeBlobClosure roots_in_blobs(&roots_closure, CodeBlobToOopClosure::FixRelocations);
 303 
 304     thread->oops_do(&roots_closure, &roots_in_blobs);
 305 
 306     // Do the real work
 307     pm->drain_stacks(false);
 308   }
 309 };
 310 
 311 class ScavengeRootsTask : public AbstractGangTask {
 312   StrongRootsScope _strong_roots_scope; // needed for Threads::possibly_parallel_threads_do
 313   SequentialSubTasksDone _subtasks;
 314   PSOldGen* _old_gen;
 315   HeapWord* _gen_top;
 316   uint _active_workers;
 317   bool _is_empty;
 318   TaskTerminator _terminator;
 319 
 320 public:
 321   ScavengeRootsTask(PSOldGen* old_gen,
 322                     HeapWord* gen_top,
 323                     uint active_workers,
 324                     bool is_empty) :
 325       AbstractGangTask("ScavengeRootsTask"),
 326       _strong_roots_scope(active_workers),
 327       _subtasks(),
 328       _old_gen(old_gen),
 329       _gen_top(gen_top),
 330       _active_workers(active_workers),
 331       _is_empty(is_empty),
 332       _terminator(active_workers, PSPromotionManager::vm_thread_promotion_manager()->stack_array_depth()) {
 333     _subtasks.set_n_threads(active_workers);
 334     _subtasks.set_n_tasks(ParallelRootType::sentinel);
 335   }
 336 
 337   virtual void work(uint worker_id) {
 338     ResourceMark rm;
 339 
 340     if (!_is_empty) {
 341       // There are only old-to-young pointers if there are objects
 342       // in the old gen.
 343 
 344       assert(_old_gen != NULL, "Sanity");
 345       // There are no old-to-young pointers if the old gen is empty.
 346       assert(!_old_gen->object_space()->is_empty(), "Should not be called is there is no work");
 347       assert(_old_gen->object_space()->contains(_gen_top) || _gen_top == _old_gen->object_space()->top(), "Sanity");
 348       assert(worker_id < ParallelGCThreads, "Sanity");
 349 
 350       {
 351         PSPromotionManager* pm = PSPromotionManager::gc_thread_promotion_manager(worker_id);
 352         PSCardTable* card_table = ParallelScavengeHeap::heap()->card_table();
 353 
 354         card_table->scavenge_contents_parallel(_old_gen->start_array(),
 355                                                _old_gen->object_space(),
 356                                                _gen_top,
 357                                                pm,
 358                                                worker_id,
 359                                                _active_workers);
 360 
 361         // Do the real work
 362         pm->drain_stacks(false);
 363       }
 364     }
 365 
 366     for (uint root_type = 0; _subtasks.try_claim_task(root_type); /* empty */ ) {
 367       scavenge_roots_work(static_cast<ParallelRootType::Value>(root_type), worker_id);
 368     }
 369     _subtasks.all_tasks_completed();
 370 
 371     PSThreadRootsTaskClosure closure(worker_id);
 372     Threads::possibly_parallel_threads_do(true /*parallel */, &closure);
 373 
 374 
 375     // If active_workers can exceed 1, add a steal_work().
 376     // PSPromotionManager::drain_stacks_depth() does not fully drain its
 377     // stacks and expects a steal_work() to complete the draining if
 378     // ParallelGCThreads is > 1.
 379 
 380     if (_active_workers > 1) {
 381       steal_work(_terminator, worker_id);
 382     }
 383   }
 384 };
 385 
 386 // This method contains no policy. You should probably
 387 // be calling invoke() instead.
 388 bool PSScavenge::invoke_no_policy() {
 389   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 390   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
 391 
 392   _gc_timer.register_gc_start();
 393 
 394   TimeStamp scavenge_entry;
 395   TimeStamp scavenge_midpoint;
 396   TimeStamp scavenge_exit;
 397 
 398   scavenge_entry.update();
 399 
 400   if (GCLocker::check_active_before_gc()) {
 401     return false;
 402   }
 403 
 404   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 405   GCCause::Cause gc_cause = heap->gc_cause();
 406 
 407   // Check for potential problems.
 408   if (!should_attempt_scavenge()) {
 409     return false;
 410   }
 411 
 412   GCIdMark gc_id_mark;
 413   _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());
 414 
 415   bool promotion_failure_occurred = false;
 416 
 417   PSYoungGen* young_gen = heap->young_gen();
 418   PSOldGen* old_gen = heap->old_gen();
 419   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
 420 
 421   heap->increment_total_collections();
 422 
 423   if (AdaptiveSizePolicy::should_update_eden_stats(gc_cause)) {
 424     // Gather the feedback data for eden occupancy.
 425     young_gen->eden_space()->accumulate_statistics();
 426   }
 427 
 428   heap->print_heap_before_gc();
 429   heap->trace_heap_before_gc(&_gc_tracer);
 430 
 431   assert(!NeverTenure || _tenuring_threshold == markWord::max_age + 1, "Sanity");
 432   assert(!AlwaysTenure || _tenuring_threshold == 0, "Sanity");
 433 
 434   // Fill in TLABs
 435   heap->ensure_parsability(true);  // retire TLABs
 436 
 437   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
 438     HandleMark hm;  // Discard invalid handles created during verification
 439     Universe::verify("Before GC");
 440   }
 441 
 442   {
 443     ResourceMark rm;
 444     HandleMark hm;
 445 
 446     GCTraceCPUTime tcpu;
 447     GCTraceTime(Info, gc) tm("Pause Young", NULL, gc_cause, true);
 448     TraceCollectorStats tcs(counters());
 449     TraceMemoryManagerStats tms(heap->young_gc_manager(), gc_cause);
 450 
 451     if (log_is_enabled(Debug, gc, heap, exit)) {
 452       accumulated_time()->start();
 453     }
 454 
 455     // Let the size policy know we're starting
 456     size_policy->minor_collection_begin();
 457 
 458     // Verify the object start arrays.
 459     if (VerifyObjectStartArray &&
 460         VerifyBeforeGC) {
 461       old_gen->verify_object_start_array();
 462     }
 463 
 464     // Verify no unmarked old->young roots
 465     if (VerifyRememberedSets) {
 466       heap->card_table()->verify_all_young_refs_imprecise();
 467     }
 468 
 469     assert(young_gen->to_space()->is_empty(),
 470            "Attempt to scavenge with live objects in to_space");
 471     young_gen->to_space()->clear(SpaceDecorator::Mangle);
 472 
 473     save_to_space_top_before_gc();
 474 
 475 #if COMPILER2_OR_JVMCI
 476     DerivedPointerTable::clear();
 477 #endif
 478 
 479     reference_processor()->enable_discovery();
 480     reference_processor()->setup_policy(false);
 481 
 482     const PreGenGCValues pre_gc_values = heap->get_pre_gc_values();
 483 
 484     // Reset our survivor overflow.
 485     set_survivor_overflow(false);
 486 
 487     // We need to save the old top values before
 488     // creating the promotion_manager. We pass the top
 489     // values to the card_table, to prevent it from
 490     // straying into the promotion labs.
 491     HeapWord* old_top = old_gen->object_space()->top();
 492 
 493     const uint active_workers =
 494       WorkerPolicy::calc_active_workers(ParallelScavengeHeap::heap()->workers().total_workers(),
 495                                         ParallelScavengeHeap::heap()->workers().active_workers(),
 496                                         Threads::number_of_non_daemon_threads());
 497     ParallelScavengeHeap::heap()->workers().update_active_workers(active_workers);
 498 
 499     PSPromotionManager::pre_scavenge();
 500 
 501     // We'll use the promotion manager again later.
 502     PSPromotionManager* promotion_manager = PSPromotionManager::vm_thread_promotion_manager();
 503     {
 504       GCTraceTime(Debug, gc, phases) tm("Scavenge", &_gc_timer);
 505 
 506       ScavengeRootsTask task(old_gen, old_top, active_workers, old_gen->object_space()->is_empty());
 507       ParallelScavengeHeap::heap()->workers().run_task(&task);
 508     }
 509 
 510     scavenge_midpoint.update();
 511 
 512     // Process reference objects discovered during scavenge
 513     {
 514       GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer);
 515 
 516       reference_processor()->setup_policy(false); // not always_clear
 517       reference_processor()->set_active_mt_degree(active_workers);
 518       PSKeepAliveClosure keep_alive(promotion_manager);
 519       PSEvacuateFollowersClosure evac_followers(promotion_manager);
 520       ReferenceProcessorStats stats;
 521       ReferenceProcessorPhaseTimes pt(&_gc_timer, reference_processor()->max_num_queues());
 522       if (reference_processor()->processing_is_mt()) {
 523         PSRefProcTaskExecutor task_executor;
 524         stats = reference_processor()->process_discovered_references(
 525           &_is_alive_closure, &keep_alive, &evac_followers, &task_executor,
 526           &pt);
 527       } else {
 528         stats = reference_processor()->process_discovered_references(
 529           &_is_alive_closure, &keep_alive, &evac_followers, NULL, &pt);
 530       }
 531 
 532       _gc_tracer.report_gc_reference_stats(stats);
 533       pt.print_all_references();
 534     }
 535 
 536     assert(promotion_manager->stacks_empty(),"stacks should be empty at this point");
 537 
 538     PSScavengeRootsClosure root_closure(promotion_manager);
 539 
 540     {
 541       GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer);
 542       WeakProcessor::weak_oops_do(&_is_alive_closure, &root_closure);
 543     }
 544 
 545     // Verify that usage of root_closure didn't copy any objects.
 546     assert(promotion_manager->stacks_empty(),"stacks should be empty at this point");
 547 
 548     // Finally, flush the promotion_manager's labs, and deallocate its stacks.
 549     promotion_failure_occurred = PSPromotionManager::post_scavenge(_gc_tracer);
 550     if (promotion_failure_occurred) {
 551       clean_up_failed_promotion();
 552       log_info(gc, promotion)("Promotion failed");
 553     }
 554 
 555     _gc_tracer.report_tenuring_threshold(tenuring_threshold());
 556 
 557     // Let the size policy know we're done.  Note that we count promotion
 558     // failure cleanup time as part of the collection (otherwise, we're
 559     // implicitly saying it's mutator time).
 560     size_policy->minor_collection_end(gc_cause);
 561 
 562     if (!promotion_failure_occurred) {
 563       // Swap the survivor spaces.
 564       young_gen->eden_space()->clear(SpaceDecorator::Mangle);
 565       young_gen->from_space()->clear(SpaceDecorator::Mangle);
 566       young_gen->swap_spaces();
 567 
 568       size_t survived = young_gen->from_space()->used_in_bytes();
 569       size_t promoted = old_gen->used_in_bytes() - pre_gc_values.old_gen_used();
 570       size_policy->update_averages(_survivor_overflow, survived, promoted);
 571 
 572       // A successful scavenge should restart the GC time limit count which is
 573       // for full GC's.
 574       size_policy->reset_gc_overhead_limit_count();
 575       if (UseAdaptiveSizePolicy) {
 576         // Calculate the new survivor size and tenuring threshold
 577 
 578         log_debug(gc, ergo)("AdaptiveSizeStart:  collection: %d ", heap->total_collections());
 579         log_trace(gc, ergo)("old_gen_capacity: " SIZE_FORMAT " young_gen_capacity: " SIZE_FORMAT,
 580                             old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
 581 
 582         if (UsePerfData) {
 583           PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters();
 584           counters->update_old_eden_size(
 585             size_policy->calculated_eden_size_in_bytes());
 586           counters->update_old_promo_size(
 587             size_policy->calculated_promo_size_in_bytes());
 588           counters->update_old_capacity(old_gen->capacity_in_bytes());
 589           counters->update_young_capacity(young_gen->capacity_in_bytes());
 590           counters->update_survived(survived);
 591           counters->update_promoted(promoted);
 592           counters->update_survivor_overflowed(_survivor_overflow);
 593         }
 594 
 595         size_t max_young_size = young_gen->max_gen_size();
 596 
 597         // Deciding a free ratio in the young generation is tricky, so if
 598         // MinHeapFreeRatio or MaxHeapFreeRatio are in use (implicating
 599         // that the old generation size may have been limited because of them) we
 600         // should then limit our young generation size using NewRatio to have it
 601         // follow the old generation size.
 602         if (MinHeapFreeRatio != 0 || MaxHeapFreeRatio != 100) {
 603           max_young_size = MIN2(old_gen->capacity_in_bytes() / NewRatio,
 604                                 young_gen->max_gen_size());
 605         }
 606 
 607         size_t survivor_limit =
 608           size_policy->max_survivor_size(max_young_size);
 609         _tenuring_threshold =
 610           size_policy->compute_survivor_space_size_and_threshold(
 611                                                            _survivor_overflow,
 612                                                            _tenuring_threshold,
 613                                                            survivor_limit);
 614 
 615        log_debug(gc, age)("Desired survivor size " SIZE_FORMAT " bytes, new threshold %u (max threshold " UINTX_FORMAT ")",
 616                           size_policy->calculated_survivor_size_in_bytes(),
 617                           _tenuring_threshold, MaxTenuringThreshold);
 618 
 619         if (UsePerfData) {
 620           PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters();
 621           counters->update_tenuring_threshold(_tenuring_threshold);
 622           counters->update_survivor_size_counters();
 623         }
 624 
 625         // Do call at minor collections?
 626         // Don't check if the size_policy is ready at this
 627         // level.  Let the size_policy check that internally.
 628         if (UseAdaptiveGenerationSizePolicyAtMinorCollection &&
 629             AdaptiveSizePolicy::should_update_eden_stats(gc_cause)) {
 630           // Calculate optimal free space amounts
 631           assert(young_gen->max_gen_size() >
 632                  young_gen->from_space()->capacity_in_bytes() +
 633                  young_gen->to_space()->capacity_in_bytes(),
 634                  "Sizes of space in young gen are out-of-bounds");
 635 
 636           size_t young_live = young_gen->used_in_bytes();
 637           size_t eden_live = young_gen->eden_space()->used_in_bytes();
 638           size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();
 639           size_t max_old_gen_size = old_gen->max_gen_size();
 640           size_t max_eden_size = max_young_size -
 641             young_gen->from_space()->capacity_in_bytes() -
 642             young_gen->to_space()->capacity_in_bytes();
 643 
 644           // Used for diagnostics
 645           size_policy->clear_generation_free_space_flags();
 646 
 647           size_policy->compute_eden_space_size(young_live,
 648                                                eden_live,
 649                                                cur_eden,
 650                                                max_eden_size,
 651                                                false /* not full gc*/);
 652 
 653           size_policy->check_gc_overhead_limit(eden_live,
 654                                                max_old_gen_size,
 655                                                max_eden_size,
 656                                                false /* not full gc*/,
 657                                                gc_cause,
 658                                                heap->soft_ref_policy());
 659 
 660           size_policy->decay_supplemental_growth(false /* not full gc*/);
 661         }
 662         // Resize the young generation at every collection
 663         // even if new sizes have not been calculated.  This is
 664         // to allow resizes that may have been inhibited by the
 665         // relative location of the "to" and "from" spaces.
 666 
 667         // Resizing the old gen at young collections can cause increases
 668         // that don't feed back to the generation sizing policy until
 669         // a full collection.  Don't resize the old gen here.
 670 
 671         heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
 672                         size_policy->calculated_survivor_size_in_bytes());
 673 
 674         log_debug(gc, ergo)("AdaptiveSizeStop: collection: %d ", heap->total_collections());
 675       }
 676 
 677       // Update the structure of the eden. With NUMA-eden CPU hotplugging or offlining can
 678       // cause the change of the heap layout. Make sure eden is reshaped if that's the case.
 679       // Also update() will case adaptive NUMA chunk resizing.
 680       assert(young_gen->eden_space()->is_empty(), "eden space should be empty now");
 681       young_gen->eden_space()->update();
 682 
 683       heap->gc_policy_counters()->update_counters();
 684 
 685       heap->resize_all_tlabs();
 686 
 687       assert(young_gen->to_space()->is_empty(), "to space should be empty now");
 688     }
 689 
 690 #if COMPILER2_OR_JVMCI
 691     DerivedPointerTable::update_pointers();
 692 #endif
 693 
 694     NOT_PRODUCT(reference_processor()->verify_no_references_recorded());
 695 
 696     // Re-verify object start arrays
 697     if (VerifyObjectStartArray &&
 698         VerifyAfterGC) {
 699       old_gen->verify_object_start_array();
 700     }
 701 
 702     // Verify all old -> young cards are now precise
 703     if (VerifyRememberedSets) {
 704       // Precise verification will give false positives. Until this is fixed,
 705       // use imprecise verification.
 706       // heap->card_table()->verify_all_young_refs_precise();
 707       heap->card_table()->verify_all_young_refs_imprecise();
 708     }
 709 
 710     if (log_is_enabled(Debug, gc, heap, exit)) {
 711       accumulated_time()->stop();
 712     }
 713 
 714     heap->print_heap_change(pre_gc_values);
 715 
 716     // Track memory usage and detect low memory
 717     MemoryService::track_memory_usage();
 718     heap->update_counters();
 719   }
 720 
 721   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
 722     HandleMark hm;  // Discard invalid handles created during verification
 723     Universe::verify("After GC");
 724   }
 725 
 726   heap->print_heap_after_gc();
 727   heap->trace_heap_after_gc(&_gc_tracer);
 728 
 729   scavenge_exit.update();
 730 
 731   log_debug(gc, task, time)("VM-Thread " JLONG_FORMAT " " JLONG_FORMAT " " JLONG_FORMAT,
 732                             scavenge_entry.ticks(), scavenge_midpoint.ticks(),
 733                             scavenge_exit.ticks());
 734 
 735   AdaptiveSizePolicyOutput::print(size_policy, heap->total_collections());
 736 
 737   _gc_timer.register_gc_end();
 738 
 739   _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());
 740 
 741   return !promotion_failure_occurred;
 742 }
 743 
 744 // This method iterates over all objects in the young generation,
 745 // removing all forwarding references. It then restores any preserved marks.
 746 void PSScavenge::clean_up_failed_promotion() {
 747   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 748   PSYoungGen* young_gen = heap->young_gen();
 749 
 750   RemoveForwardedPointerClosure remove_fwd_ptr_closure;
 751   young_gen->object_iterate(&remove_fwd_ptr_closure);
 752 
 753   PSPromotionManager::restore_preserved_marks();
 754 
 755   // Reset the PromotionFailureALot counters.
 756   NOT_PRODUCT(heap->reset_promotion_should_fail();)
 757 }
 758 
 759 bool PSScavenge::should_attempt_scavenge() {
 760   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 761   PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters();
 762 
 763   if (UsePerfData) {
 764     counters->update_scavenge_skipped(not_skipped);
 765   }
 766 
 767   PSYoungGen* young_gen = heap->young_gen();
 768   PSOldGen* old_gen = heap->old_gen();
 769 
 770   // Do not attempt to promote unless to_space is empty
 771   if (!young_gen->to_space()->is_empty()) {
 772     _consecutive_skipped_scavenges++;
 773     if (UsePerfData) {
 774       counters->update_scavenge_skipped(to_space_not_empty);
 775     }
 776     return false;
 777   }
 778 
 779   // Test to see if the scavenge will likely fail.
 780   PSAdaptiveSizePolicy* policy = heap->size_policy();
 781 
 782   // A similar test is done in the policy's should_full_GC().  If this is
 783   // changed, decide if that test should also be changed.
 784   size_t avg_promoted = (size_t) policy->padded_average_promoted_in_bytes();
 785   size_t promotion_estimate = MIN2(avg_promoted, young_gen->used_in_bytes());
 786   bool result = promotion_estimate < old_gen->free_in_bytes();
 787 
 788   log_trace(ergo)("%s scavenge: average_promoted " SIZE_FORMAT " padded_average_promoted " SIZE_FORMAT " free in old gen " SIZE_FORMAT,
 789                 result ? "Do" : "Skip", (size_t) policy->average_promoted_in_bytes(),
 790                 (size_t) policy->padded_average_promoted_in_bytes(),
 791                 old_gen->free_in_bytes());
 792   if (young_gen->used_in_bytes() < (size_t) policy->padded_average_promoted_in_bytes()) {
 793     log_trace(ergo)(" padded_promoted_average is greater than maximum promotion = " SIZE_FORMAT, young_gen->used_in_bytes());
 794   }
 795 
 796   if (result) {
 797     _consecutive_skipped_scavenges = 0;
 798   } else {
 799     _consecutive_skipped_scavenges++;
 800     if (UsePerfData) {
 801       counters->update_scavenge_skipped(promoted_too_large);
 802     }
 803   }
 804   return result;
 805 }
 806 
 807 // Adaptive size policy support.
 808 void PSScavenge::set_young_generation_boundary(HeapWord* v) {
 809   _young_generation_boundary = v;
 810   if (UseCompressedOops) {
 811     _young_generation_boundary_compressed = (uintptr_t)CompressedOops::encode((oop)v);
 812   }
 813 }
 814 
 815 void PSScavenge::initialize() {
 816   // Arguments must have been parsed
 817 
 818   if (AlwaysTenure || NeverTenure) {
 819     assert(MaxTenuringThreshold == 0 || MaxTenuringThreshold == markWord::max_age + 1,
 820            "MaxTenuringThreshold should be 0 or markWord::max_age + 1, but is %d", (int) MaxTenuringThreshold);
 821     _tenuring_threshold = MaxTenuringThreshold;
 822   } else {
 823     // We want to smooth out our startup times for the AdaptiveSizePolicy
 824     _tenuring_threshold = (UseAdaptiveSizePolicy) ? InitialTenuringThreshold :
 825                                                     MaxTenuringThreshold;
 826   }
 827 
 828   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 829   PSYoungGen* young_gen = heap->young_gen();
 830   PSOldGen* old_gen = heap->old_gen();
 831 
 832   // Set boundary between young_gen and old_gen
 833   assert(old_gen->reserved().end() <= young_gen->eden_space()->bottom(),
 834          "old above young");
 835   set_young_generation_boundary(young_gen->eden_space()->bottom());
 836 
 837   // Initialize ref handling object for scavenging.
 838   _span_based_discoverer.set_span(young_gen->reserved());
 839   _ref_processor =
 840     new ReferenceProcessor(&_span_based_discoverer,
 841                            ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing
 842                            ParallelGCThreads,          // mt processing degree
 843                            true,                       // mt discovery
 844                            ParallelGCThreads,          // mt discovery degree
 845                            true,                       // atomic_discovery
 846                            NULL,                       // header provides liveness info
 847                            false);
 848 
 849   // Cache the cardtable
 850   _card_table = heap->card_table();
 851 
 852   _counters = new CollectorCounters("Parallel young collection pauses", 0);
 853 }