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