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