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