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