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