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