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