1 /*
  2  * Copyright Amazon.com Inc. 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 
 26 #include "precompiled.hpp"
 27 
 28 #include "gc/shared/strongRootsScope.hpp"
 29 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
 30 #include "gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp"
 31 #include "gc/shenandoah/shenandoahAsserts.hpp"
 32 #include "gc/shenandoah/shenandoahFreeSet.hpp"
 33 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp"
 34 #include "gc/shenandoah/shenandoahHeap.hpp"
 35 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 36 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
 37 #include "gc/shenandoah/shenandoahHeapRegionClosures.hpp"
 38 #include "gc/shenandoah/shenandoahMarkClosures.hpp"
 39 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
 40 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
 41 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
 42 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
 43 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
 44 #include "gc/shenandoah/shenandoahUtils.hpp"
 45 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
 46 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
 47 #include "runtime/threads.hpp"
 48 #include "utilities/events.hpp"
 49 
 50 class ShenandoahFlushAllSATB : public ThreadClosure {
 51 private:
 52   SATBMarkQueueSet& _satb_qset;
 53 
 54 public:
 55   explicit ShenandoahFlushAllSATB(SATBMarkQueueSet& satb_qset) :
 56     _satb_qset(satb_qset) {}
 57 
 58   void do_thread(Thread* thread) override {
 59     // Transfer any partial buffer to the qset for completed buffer processing.
 60     _satb_qset.flush_queue(ShenandoahThreadLocalData::satb_mark_queue(thread));
 61   }
 62 };
 63 
 64 class ShenandoahProcessOldSATB : public SATBBufferClosure {
 65 private:
 66   ShenandoahObjToScanQueue*       _queue;
 67   ShenandoahHeap*                 _heap;
 68   ShenandoahMarkingContext* const _mark_context;
 69   size_t                          _trashed_oops;
 70 
 71 public:
 72   explicit ShenandoahProcessOldSATB(ShenandoahObjToScanQueue* q) :
 73     _queue(q),
 74     _heap(ShenandoahHeap::heap()),
 75     _mark_context(_heap->marking_context()),
 76     _trashed_oops(0) {}
 77 
 78   void do_buffer(void** buffer, size_t size) override {
 79     assert(size == 0 || !_heap->has_forwarded_objects() || _heap->is_concurrent_old_mark_in_progress(), "Forwarded objects are not expected here");
 80     for (size_t i = 0; i < size; ++i) {
 81       oop *p = (oop *) &buffer[i];
 82       ShenandoahHeapRegion* region = _heap->heap_region_containing(*p);
 83       if (region->is_old() && region->is_active()) {
 84           ShenandoahMark::mark_through_ref<oop, OLD>(p, _queue, nullptr, _mark_context, false);
 85       } else {
 86         _trashed_oops++;
 87       }
 88     }
 89   }
 90 
 91   size_t trashed_oops() const {
 92     return _trashed_oops;
 93   }
 94 };
 95 
 96 class ShenandoahPurgeSATBTask : public WorkerTask {
 97 private:
 98   ShenandoahObjToScanQueueSet* _mark_queues;
 99   volatile size_t             _trashed_oops;
100 
101 public:
102   explicit ShenandoahPurgeSATBTask(ShenandoahObjToScanQueueSet* queues) :
103     WorkerTask("Purge SATB"),
104     _mark_queues(queues),
105     _trashed_oops(0) {
106     Threads::change_thread_claim_token();
107   }
108 
109   ~ShenandoahPurgeSATBTask() {
110     if (_trashed_oops > 0) {
111       log_info(gc)("Purged " SIZE_FORMAT " oops from old generation SATB buffers", _trashed_oops);
112     }
113   }
114 
115   void work(uint worker_id) override {
116     ShenandoahParallelWorkerSession worker_session(worker_id);
117     ShenandoahSATBMarkQueueSet &satb_queues = ShenandoahBarrierSet::satb_mark_queue_set();
118     ShenandoahFlushAllSATB flusher(satb_queues);
119     Threads::possibly_parallel_threads_do(true /* is_par */, &flusher);
120 
121     ShenandoahObjToScanQueue* mark_queue = _mark_queues->queue(worker_id);
122     ShenandoahProcessOldSATB processor(mark_queue);
123     while (satb_queues.apply_closure_to_completed_buffer(&processor)) {}
124 
125     Atomic::add(&_trashed_oops, processor.trashed_oops());
126   }
127 };
128 
129 class ShenandoahConcurrentCoalesceAndFillTask : public WorkerTask {
130 private:
131   uint                    _nworkers;
132   ShenandoahHeapRegion**  _coalesce_and_fill_region_array;
133   uint                    _coalesce_and_fill_region_count;
134   volatile bool           _is_preempted;
135 
136 public:
137   ShenandoahConcurrentCoalesceAndFillTask(uint nworkers,
138                                           ShenandoahHeapRegion** coalesce_and_fill_region_array,
139                                           uint region_count) :
140     WorkerTask("Shenandoah Concurrent Coalesce and Fill"),
141     _nworkers(nworkers),
142     _coalesce_and_fill_region_array(coalesce_and_fill_region_array),
143     _coalesce_and_fill_region_count(region_count),
144     _is_preempted(false) {
145   }
146 
147   void work(uint worker_id) override {
148     ShenandoahWorkerTimingsTracker timer(ShenandoahPhaseTimings::conc_coalesce_and_fill, ShenandoahPhaseTimings::ScanClusters, worker_id);
149     for (uint region_idx = worker_id; region_idx < _coalesce_and_fill_region_count; region_idx += _nworkers) {
150       ShenandoahHeapRegion* r = _coalesce_and_fill_region_array[region_idx];
151       if (r->is_humongous()) {
152         // There is only one object in this region and it is not garbage,
153         // so no need to coalesce or fill.
154         continue;
155       }
156 
157       if (!r->oop_coalesce_and_fill(true)) {
158         // Coalesce and fill has been preempted
159         Atomic::store(&_is_preempted, true);
160         return;
161       }
162     }
163   }
164 
165   // Value returned from is_completed() is only valid after all worker thread have terminated.
166   bool is_completed() {
167     return !Atomic::load(&_is_preempted);
168   }
169 };
170 
171 ShenandoahOldGeneration::ShenandoahOldGeneration(uint max_queues, size_t max_capacity, size_t soft_max_capacity)
172   : ShenandoahGeneration(OLD, max_queues, max_capacity, soft_max_capacity),
173     _coalesce_and_fill_region_array(NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, ShenandoahHeap::heap()->num_regions(), mtGC)),
174     _old_heuristics(nullptr),
175     _region_balance(0),
176     _promoted_reserve(0),
177     _promoted_expended(0),
178     _promotion_potential(0),
179     _pad_for_promote_in_place(0),
180     _promotable_humongous_regions(0),
181     _promotable_regular_regions(0),
182     _is_parseable(true),
183     _card_scan(nullptr),
184     _state(WAITING_FOR_BOOTSTRAP),
185     _growth_before_compaction(INITIAL_GROWTH_BEFORE_COMPACTION),
186     _min_growth_before_compaction ((ShenandoahMinOldGenGrowthPercent * FRACTIONAL_DENOMINATOR) / 100)
187 {
188   _live_bytes_after_last_mark = ShenandoahHeap::heap()->capacity() * INITIAL_LIVE_FRACTION / FRACTIONAL_DENOMINATOR;
189   // Always clear references for old generation
190   ref_processor()->set_soft_reference_policy(true);
191 
192   if (ShenandoahCardBarrier) {
193     // TODO: Old and young generations should only be instantiated for generational mode
194     ShenandoahCardTable* card_table = ShenandoahBarrierSet::barrier_set()->card_table();
195     size_t card_count = card_table->cards_required(ShenandoahHeap::heap()->reserved_region().word_size());
196     auto rs = new ShenandoahDirectCardMarkRememberedSet(card_table, card_count);
197     _card_scan = new ShenandoahScanRemembered<ShenandoahDirectCardMarkRememberedSet>(rs);
198   }
199 }
200 
201 void ShenandoahOldGeneration::set_promoted_reserve(size_t new_val) {
202   shenandoah_assert_heaplocked_or_safepoint();
203   _promoted_reserve = new_val;
204 }
205 
206 size_t ShenandoahOldGeneration::get_promoted_reserve() const {
207   return _promoted_reserve;
208 }
209 
210 void ShenandoahOldGeneration::augment_promoted_reserve(size_t increment) {
211   shenandoah_assert_heaplocked_or_safepoint();
212   _promoted_reserve += increment;
213 }
214 
215 void ShenandoahOldGeneration::reset_promoted_expended() {
216   shenandoah_assert_heaplocked_or_safepoint();
217   Atomic::store(&_promoted_expended, (size_t) 0);
218 }
219 
220 size_t ShenandoahOldGeneration::expend_promoted(size_t increment) {
221   shenandoah_assert_heaplocked_or_safepoint();
222   assert(get_promoted_expended() + increment <= get_promoted_reserve(), "Do not expend more promotion than budgeted");
223   return Atomic::add(&_promoted_expended, increment);
224 }
225 
226 size_t ShenandoahOldGeneration::unexpend_promoted(size_t decrement) {
227   return Atomic::sub(&_promoted_expended, decrement);
228 }
229 
230 size_t ShenandoahOldGeneration::get_promoted_expended() const {
231   return Atomic::load(&_promoted_expended);
232 }
233 
234 bool ShenandoahOldGeneration::can_allocate(const ShenandoahAllocRequest &req) const {
235   assert(req.type() != ShenandoahAllocRequest::_alloc_gclab, "GCLAB pertains only to young-gen memory");
236 
237   const size_t requested_bytes = req.size() * HeapWordSize;
238   // The promotion reserve may also be used for evacuations. If we can promote this object,
239   // then we can also evacuate it.
240   if (can_promote(requested_bytes)) {
241     // The promotion reserve should be able to accommodate this request. The request
242     // might still fail if alignment with the card table increases the size. The request
243     // may also fail if the heap is badly fragmented and the free set cannot find room for it.
244     return true;
245   }
246 
247   if (req.type() == ShenandoahAllocRequest::_alloc_plab) {
248     // The promotion reserve cannot accommodate this plab request. Check if we still have room for
249     // evacuations. Note that we cannot really know how much of the plab will be used for evacuations,
250     // so here we only check that some evacuation reserve still exists.
251     return get_evacuation_reserve() > 0;
252   }
253 
254   // This is a shared allocation request. We've already checked that it can't be promoted, so if
255   // it is a promotion, we return false. Otherwise, it is a shared evacuation request, and we allow
256   // the allocation to proceed.
257   return !req.is_promotion();
258 }
259 
260 void
261 ShenandoahOldGeneration::configure_plab_for_current_thread(const ShenandoahAllocRequest &req) {
262   // Note: Even when a mutator is performing a promotion outside a LAB, we use a 'shared_gc' request.
263   if (req.is_gc_alloc()) {
264     const size_t actual_size = req.actual_size() * HeapWordSize;
265     if (req.type() ==  ShenandoahAllocRequest::_alloc_plab) {
266       // We've created a new plab. Now we configure it whether it will be used for promotions
267       // and evacuations - or just evacuations.
268       Thread* thread = Thread::current();
269       ShenandoahThreadLocalData::reset_plab_promoted(thread);
270 
271       // The actual size of the allocation may be larger than the requested bytes (due to alignment on card boundaries).
272       // If this puts us over our promotion budget, we need to disable future PLAB promotions for this thread.
273       if (can_promote(actual_size)) {
274         // Assume the entirety of this PLAB will be used for promotion.  This prevents promotion from overreach.
275         // When we retire this plab, we'll unexpend what we don't really use.
276         expend_promoted(actual_size);
277         ShenandoahThreadLocalData::enable_plab_promotions(thread);
278         ShenandoahThreadLocalData::set_plab_actual_size(thread, actual_size);
279       } else {
280         // Disable promotions in this thread because entirety of this PLAB must be available to hold old-gen evacuations.
281         ShenandoahThreadLocalData::disable_plab_promotions(thread);
282         ShenandoahThreadLocalData::set_plab_actual_size(thread, 0);
283       }
284     } else if (req.is_promotion()) {
285       // Shared promotion.
286       expend_promoted(actual_size);
287     }
288   }
289 }
290 
291 size_t ShenandoahOldGeneration::get_live_bytes_after_last_mark() const {
292   return _live_bytes_after_last_mark;
293 }
294 
295 void ShenandoahOldGeneration::set_live_bytes_after_last_mark(size_t bytes) {
296   if (bytes == 0) {
297     // Restart search for best old-gen size to the initial state
298     _live_bytes_after_last_mark = ShenandoahHeap::heap()->capacity() * INITIAL_LIVE_FRACTION / FRACTIONAL_DENOMINATOR;
299     _growth_before_compaction = INITIAL_GROWTH_BEFORE_COMPACTION;
300   } else {
301     _live_bytes_after_last_mark = bytes;
302     _growth_before_compaction /= 2;
303     if (_growth_before_compaction < _min_growth_before_compaction) {
304       _growth_before_compaction = _min_growth_before_compaction;
305     }
306   }
307 }
308 
309 void ShenandoahOldGeneration::handle_failed_transfer() {
310   _old_heuristics->trigger_cannot_expand();
311 }
312 
313 size_t ShenandoahOldGeneration::usage_trigger_threshold() const {
314   size_t result = _live_bytes_after_last_mark + (_live_bytes_after_last_mark * _growth_before_compaction) / FRACTIONAL_DENOMINATOR;
315   return result;
316 }
317 
318 bool ShenandoahOldGeneration::contains(ShenandoahHeapRegion* region) const {
319   // TODO: Should this be region->is_old() instead?
320   return !region->is_young();
321 }
322 
323 void ShenandoahOldGeneration::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* cl) {
324   ShenandoahIncludeRegionClosure<OLD_GENERATION> old_regions_cl(cl);
325   ShenandoahHeap::heap()->parallel_heap_region_iterate(&old_regions_cl);
326 }
327 
328 void ShenandoahOldGeneration::heap_region_iterate(ShenandoahHeapRegionClosure* cl) {
329   ShenandoahIncludeRegionClosure<OLD_GENERATION> old_regions_cl(cl);
330   ShenandoahHeap::heap()->heap_region_iterate(&old_regions_cl);
331 }
332 
333 void ShenandoahOldGeneration::set_concurrent_mark_in_progress(bool in_progress) {
334   ShenandoahHeap::heap()->set_concurrent_old_mark_in_progress(in_progress);
335 }
336 
337 bool ShenandoahOldGeneration::is_concurrent_mark_in_progress() {
338   return ShenandoahHeap::heap()->is_concurrent_old_mark_in_progress();
339 }
340 
341 void ShenandoahOldGeneration::cancel_marking() {
342   if (is_concurrent_mark_in_progress()) {
343     log_info(gc)("Abandon SATB buffers");
344     ShenandoahBarrierSet::satb_mark_queue_set().abandon_partial_marking();
345   }
346 
347   ShenandoahGeneration::cancel_marking();
348 }
349 
350 void ShenandoahOldGeneration::cancel_gc() {
351   shenandoah_assert_safepoint();
352   if (is_idle()) {
353 #ifdef ASSERT
354     validate_waiting_for_bootstrap();
355 #endif
356   } else {
357     log_info(gc)("Terminating old gc cycle.");
358     // Stop marking
359     cancel_marking();
360     // Stop tracking old regions
361     abandon_collection_candidates();
362     // Remove old generation access to young generation mark queues
363     ShenandoahHeap::heap()->young_generation()->set_old_gen_task_queues(nullptr);
364     // Transition to IDLE now.
365     transition_to(ShenandoahOldGeneration::WAITING_FOR_BOOTSTRAP);
366   }
367 }
368 
369 void ShenandoahOldGeneration::prepare_gc() {
370   // Now that we have made the old generation parsable, it is safe to reset the mark bitmap.
371   assert(state() != FILLING, "Cannot reset old without making it parsable");
372 
373   ShenandoahGeneration::prepare_gc();
374 }
375 
376 bool ShenandoahOldGeneration::entry_coalesce_and_fill() {
377   ShenandoahHeap* const heap = ShenandoahHeap::heap();
378 
379   static const char* msg = "Coalescing and filling (OLD)";
380   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_coalesce_and_fill);
381 
382   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
383   EventMark em("%s", msg);
384   ShenandoahWorkerScope scope(heap->workers(),
385                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
386                               msg);
387 
388   return coalesce_and_fill();
389 }
390 
391 // Make the old generation regions parsable, so they can be safely
392 // scanned when looking for objects in memory indicated by dirty cards.
393 bool ShenandoahOldGeneration::coalesce_and_fill() {
394   transition_to(FILLING);
395 
396   // This code will see the same set of regions to fill on each resumption as it did
397   // on the initial run. That's okay because each region keeps track of its own coalesce
398   // and fill state. Regions that were filled on a prior attempt will not try to fill again.
399   uint coalesce_and_fill_regions_count = _old_heuristics->get_coalesce_and_fill_candidates(_coalesce_and_fill_region_array);
400   assert(coalesce_and_fill_regions_count <= ShenandoahHeap::heap()->num_regions(), "Sanity");
401   if (coalesce_and_fill_regions_count == 0) {
402     // No regions need to be filled.
403     abandon_collection_candidates();
404     return true;
405   }
406 
407   ShenandoahHeap* const heap = ShenandoahHeap::heap();
408   WorkerThreads* workers = heap->workers();
409   uint nworkers = workers->active_workers();
410   ShenandoahConcurrentCoalesceAndFillTask task(nworkers, _coalesce_and_fill_region_array, coalesce_and_fill_regions_count);
411 
412   log_info(gc)("Starting (or resuming) coalesce-and-fill of " UINT32_FORMAT " old heap regions", coalesce_and_fill_regions_count);
413   workers->run_task(&task);
414   if (task.is_completed()) {
415     // We no longer need to track regions that need to be coalesced and filled.
416     abandon_collection_candidates();
417     return true;
418   } else {
419     // Coalesce-and-fill has been preempted. We'll finish that effort in the future.  Do not invoke
420     // ShenandoahGeneration::prepare_gc() until coalesce-and-fill is done because it resets the mark bitmap
421     // and invokes set_mark_incomplete().  Coalesce-and-fill depends on the mark bitmap.
422     log_debug(gc)("Suspending coalesce-and-fill of old heap regions");
423     return false;
424   }
425 }
426 
427 void ShenandoahOldGeneration::transfer_pointers_from_satb() {
428   ShenandoahHeap* heap = ShenandoahHeap::heap();
429   shenandoah_assert_safepoint();
430   assert(heap->is_concurrent_old_mark_in_progress(), "Only necessary during old marking.");
431   log_info(gc)("Transfer SATB buffers");
432   uint nworkers = heap->workers()->active_workers();
433   StrongRootsScope scope(nworkers);
434 
435   ShenandoahPurgeSATBTask purge_satb_task(task_queues());
436   heap->workers()->run_task(&purge_satb_task);
437 }
438 
439 bool ShenandoahOldGeneration::contains(oop obj) const {
440   return ShenandoahHeap::heap()->is_in_old(obj);
441 }
442 
443 void ShenandoahOldGeneration::prepare_regions_and_collection_set(bool concurrent) {
444   ShenandoahHeap* heap = ShenandoahHeap::heap();
445   assert(!heap->is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
446 
447   {
448     ShenandoahGCPhase phase(concurrent ?
449         ShenandoahPhaseTimings::final_update_region_states :
450         ShenandoahPhaseTimings::degen_gc_final_update_region_states);
451     ShenandoahFinalMarkUpdateRegionStateClosure cl(complete_marking_context());
452 
453     parallel_heap_region_iterate(&cl);
454     heap->assert_pinned_region_status();
455   }
456 
457   {
458     // This doesn't actually choose a collection set, but prepares a list of
459     // regions as 'candidates' for inclusion in a mixed collection.
460     ShenandoahGCPhase phase(concurrent ?
461         ShenandoahPhaseTimings::choose_cset :
462         ShenandoahPhaseTimings::degen_gc_choose_cset);
463     ShenandoahHeapLocker locker(heap->lock());
464     _old_heuristics->prepare_for_old_collections();
465   }
466 
467   {
468     // Though we did not choose a collection set above, we still may have
469     // freed up immediate garbage regions so proceed with rebuilding the free set.
470     ShenandoahGCPhase phase(concurrent ?
471         ShenandoahPhaseTimings::final_rebuild_freeset :
472         ShenandoahPhaseTimings::degen_gc_final_rebuild_freeset);
473     ShenandoahHeapLocker locker(heap->lock());
474     size_t cset_young_regions, cset_old_regions;
475     size_t first_old, last_old, num_old;
476     heap->free_set()->prepare_to_rebuild(cset_young_regions, cset_old_regions, first_old, last_old, num_old);
477     // This is just old-gen completion.  No future budgeting required here.  The only reason to rebuild the freeset here
478     // is in case there was any immediate old garbage identified.
479     heap->free_set()->rebuild(cset_young_regions, cset_old_regions);
480   }
481 }
482 
483 const char* ShenandoahOldGeneration::state_name(State state) {
484   switch (state) {
485     case WAITING_FOR_BOOTSTRAP:   return "Waiting for Bootstrap";
486     case FILLING:                 return "Coalescing";
487     case BOOTSTRAPPING:           return "Bootstrapping";
488     case MARKING:                 return "Marking";
489     case EVACUATING:              return "Evacuating";
490     case EVACUATING_AFTER_GLOBAL: return "Evacuating (G)";
491     default:
492       ShouldNotReachHere();
493       return "Unknown";
494   }
495 }
496 
497 void ShenandoahOldGeneration::transition_to(State new_state) {
498   if (_state != new_state) {
499     log_info(gc)("Old generation transition from %s to %s", state_name(_state), state_name(new_state));
500     validate_transition(new_state);
501     _state = new_state;
502   }
503 }
504 
505 #ifdef ASSERT
506 // This diagram depicts the expected state transitions for marking the old generation
507 // and preparing for old collections. When a young generation cycle executes, the
508 // remembered set scan must visit objects in old regions. Visiting an object which
509 // has become dead on previous old cycles will result in crashes. To avoid visiting
510 // such objects, the remembered set scan will use the old generation mark bitmap when
511 // possible. It is _not_ possible to use the old generation bitmap when old marking
512 // is active (bitmap is not complete). For this reason, the old regions are made
513 // parsable _before_ the old generation bitmap is reset. The diagram does not depict
514 // cancellation of old collections by global or full collections.
515 //
516 // When a global collection supersedes an old collection, the global mark still
517 // "completes" the old mark bitmap. Subsequent remembered set scans may use the
518 // old generation mark bitmap, but any uncollected old regions must still be made parsable
519 // before the next old generation cycle begins. For this reason, a global collection may
520 // create mixed collection candidates and coalesce and fill candidates and will put
521 // the old generation in the respective states (EVACUATING or FILLING). After a Full GC,
522 // the mark bitmaps are all reset, all regions are parsable and the mark context will
523 // not be "complete". After a Full GC, remembered set scans will _not_ use the mark bitmap
524 // and we expect the old generation to be waiting for bootstrap.
525 //
526 //                              +-----------------+
527 //               +------------> |     FILLING     | <---+
528 //               |   +--------> |                 |     |
529 //               |   |          +-----------------+     |
530 //               |   |            |                     |
531 //               |   |            | Filling Complete    | <-> A global collection may
532 //               |   |            v                     |     move the old generation
533 //               |   |          +-----------------+     |     directly from waiting for
534 //           +-- |-- |--------> |     WAITING     |     |     bootstrap to filling or
535 //           |   |   |    +---- |  FOR BOOTSTRAP  | ----+     evacuating. It may also
536 //           |   |   |    |     +-----------------+           move from filling to waiting
537 //           |   |   |    |       |                           for bootstrap.
538 //           |   |   |    |       | Reset Bitmap
539 //           |   |   |    |       v
540 //           |   |   |    |     +-----------------+     +----------------------+
541 //           |   |   |    |     |    BOOTSTRAP    | <-> |       YOUNG GC       |
542 //           |   |   |    |     |                 |     | (RSet Parses Region) |
543 //           |   |   |    |     +-----------------+     +----------------------+
544 //           |   |   |    |       |
545 //           |   |   |    |       | Old Marking
546 //           |   |   |    |       v
547 //           |   |   |    |     +-----------------+     +----------------------+
548 //           |   |   |    |     |     MARKING     | <-> |       YOUNG GC       |
549 //           |   |   +--------- |                 |     | (RSet Parses Region) |
550 //           |   |        |     +-----------------+     +----------------------+
551 //           |   |        |       |
552 //           |   |        |       | Has Evacuation Candidates
553 //           |   |        |       v
554 //           |   |        |     +-----------------+     +--------------------+
555 //           |   |        +---> |    EVACUATING   | <-> |      YOUNG GC      |
556 //           |   +------------- |                 |     | (RSet Uses Bitmap) |
557 //           |                  +-----------------+     +--------------------+
558 //           |                    |
559 //           |                    | Global Cycle Coalesces and Fills Old Regions
560 //           |                    v
561 //           |                  +-----------------+     +--------------------+
562 //           +----------------- |    EVACUATING   | <-> |      YOUNG GC      |
563 //                              |   AFTER GLOBAL  |     | (RSet Uses Bitmap) |
564 //                              +-----------------+     +--------------------+
565 //
566 //
567 void ShenandoahOldGeneration::validate_transition(State new_state) {
568   ShenandoahGenerationalHeap* heap = ShenandoahGenerationalHeap::heap();
569   switch (new_state) {
570     case FILLING:
571       assert(_state != BOOTSTRAPPING, "Cannot begin making old regions parsable after bootstrapping");
572       assert(is_mark_complete(), "Cannot begin filling without first completing marking, state is '%s'", state_name(_state));
573       assert(_old_heuristics->has_coalesce_and_fill_candidates(), "Cannot begin filling without something to fill.");
574       break;
575     case WAITING_FOR_BOOTSTRAP:
576       // GC cancellation can send us back here from any state.
577       validate_waiting_for_bootstrap();
578       break;
579     case BOOTSTRAPPING:
580       assert(_state == WAITING_FOR_BOOTSTRAP, "Cannot reset bitmap without making old regions parsable, state is '%s'", state_name(_state));
581       assert(_old_heuristics->unprocessed_old_collection_candidates() == 0, "Cannot bootstrap with mixed collection candidates");
582       assert(!heap->is_prepare_for_old_mark_in_progress(), "Cannot still be making old regions parsable.");
583       break;
584     case MARKING:
585       assert(_state == BOOTSTRAPPING, "Must have finished bootstrapping before marking, state is '%s'", state_name(_state));
586       assert(heap->young_generation()->old_gen_task_queues() != nullptr, "Young generation needs old mark queues.");
587       assert(heap->is_concurrent_old_mark_in_progress(), "Should be marking old now.");
588       break;
589     case EVACUATING_AFTER_GLOBAL:
590       assert(_state == EVACUATING, "Must have been evacuating, state is '%s'", state_name(_state));
591       break;
592     case EVACUATING:
593       assert(_state == WAITING_FOR_BOOTSTRAP || _state == MARKING, "Cannot have old collection candidates without first marking, state is '%s'", state_name(_state));
594       assert(_old_heuristics->unprocessed_old_collection_candidates() > 0, "Must have collection candidates here.");
595       break;
596     default:
597       fatal("Unknown new state");
598   }
599 }
600 
601 bool ShenandoahOldGeneration::validate_waiting_for_bootstrap() {
602   ShenandoahHeap* heap = ShenandoahHeap::heap();
603   assert(!heap->is_concurrent_old_mark_in_progress(), "Cannot become ready for bootstrap during old mark.");
604   assert(heap->young_generation()->old_gen_task_queues() == nullptr, "Cannot become ready for bootstrap when still setup for bootstrapping.");
605   assert(!is_concurrent_mark_in_progress(), "Cannot be marking in IDLE");
606   assert(!heap->young_generation()->is_bootstrap_cycle(), "Cannot have old mark queues if IDLE");
607   assert(!_old_heuristics->has_coalesce_and_fill_candidates(), "Cannot have coalesce and fill candidates in IDLE");
608   assert(_old_heuristics->unprocessed_old_collection_candidates() == 0, "Cannot have mixed collection candidates in IDLE");
609   return true;
610 }
611 #endif
612 
613 ShenandoahHeuristics* ShenandoahOldGeneration::initialize_heuristics(ShenandoahMode* gc_mode) {
614   _old_heuristics = new ShenandoahOldHeuristics(this, ShenandoahGenerationalHeap::heap());
615   _old_heuristics->set_guaranteed_gc_interval(ShenandoahGuaranteedOldGCInterval);
616   _heuristics = _old_heuristics;
617   return _heuristics;
618 }
619 
620 void ShenandoahOldGeneration::record_success_concurrent(bool abbreviated) {
621   heuristics()->record_success_concurrent(abbreviated);
622   ShenandoahHeap::heap()->shenandoah_policy()->record_success_old();
623 }
624 
625 void ShenandoahOldGeneration::handle_failed_evacuation() {
626   if (_failed_evacuation.try_set()) {
627     log_info(gc)("Old gen evac failure.");
628   }
629 }
630 
631 void ShenandoahOldGeneration::handle_failed_promotion(Thread* thread, size_t size) {
632   // We squelch excessive reports to reduce noise in logs.
633   const size_t MaxReportsPerEpoch = 4;
634   static size_t last_report_epoch = 0;
635   static size_t epoch_report_count = 0;
636   auto heap = ShenandoahGenerationalHeap::heap();
637 
638   size_t promotion_reserve;
639   size_t promotion_expended;
640 
641   const size_t gc_id = heap->control_thread()->get_gc_id();
642 
643   if ((gc_id != last_report_epoch) || (epoch_report_count++ < MaxReportsPerEpoch)) {
644     {
645       // Promotion failures should be very rare.  Invest in providing useful diagnostic info.
646       ShenandoahHeapLocker locker(heap->lock());
647       promotion_reserve = get_promoted_reserve();
648       promotion_expended = get_promoted_expended();
649     }
650     PLAB* const plab = ShenandoahThreadLocalData::plab(thread);
651     const size_t words_remaining = (plab == nullptr)? 0: plab->words_remaining();
652     const char* promote_enabled = ShenandoahThreadLocalData::allow_plab_promotions(thread)? "enabled": "disabled";
653 
654     log_info(gc, ergo)("Promotion failed, size " SIZE_FORMAT ", has plab? %s, PLAB remaining: " SIZE_FORMAT
655                        ", plab promotions %s, promotion reserve: " SIZE_FORMAT ", promotion expended: " SIZE_FORMAT
656                        ", old capacity: " SIZE_FORMAT ", old_used: " SIZE_FORMAT ", old unaffiliated regions: " SIZE_FORMAT,
657                        size * HeapWordSize, plab == nullptr? "no": "yes",
658                        words_remaining * HeapWordSize, promote_enabled, promotion_reserve, promotion_expended,
659                        max_capacity(), used(), free_unaffiliated_regions());
660 
661     if ((gc_id == last_report_epoch) && (epoch_report_count >= MaxReportsPerEpoch)) {
662       log_info(gc, ergo)("Squelching additional promotion failure reports for current epoch");
663     } else if (gc_id != last_report_epoch) {
664       last_report_epoch = gc_id;
665       epoch_report_count = 1;
666     }
667   }
668 }
669 
670 void ShenandoahOldGeneration::handle_evacuation(HeapWord* obj, size_t words, bool promotion) {
671   // Only register the copy of the object that won the evacuation race.
672   _card_scan->register_object_without_lock(obj);
673 
674   // Mark the entire range of the evacuated object as dirty.  At next remembered set scan,
675   // we will clear dirty bits that do not hold interesting pointers.  It's more efficient to
676   // do this in batch, in a background GC thread than to try to carefully dirty only cards
677   // that hold interesting pointers right now.
678   _card_scan->mark_range_as_dirty(obj, words);
679 
680   if (promotion) {
681     // This evacuation was a promotion, track this as allocation against old gen
682     increase_allocated(words * HeapWordSize);
683   }
684 }
685 
686 bool ShenandoahOldGeneration::has_unprocessed_collection_candidates() {
687   return _old_heuristics->unprocessed_old_collection_candidates() > 0;
688 }
689 
690 size_t ShenandoahOldGeneration::unprocessed_collection_candidates_live_memory() {
691   return _old_heuristics->unprocessed_old_collection_candidates_live_memory();
692 }
693 
694 void ShenandoahOldGeneration::abandon_collection_candidates() {
695   _old_heuristics->abandon_collection_candidates();
696 }
697 
698 void ShenandoahOldGeneration::prepare_for_mixed_collections_after_global_gc() {
699   assert(is_mark_complete(), "Expected old generation mark to be complete after global cycle.");
700   _old_heuristics->prepare_for_old_collections();
701   log_info(gc)("After choosing global collection set, mixed candidates: " UINT32_FORMAT ", coalescing candidates: " SIZE_FORMAT,
702                _old_heuristics->unprocessed_old_collection_candidates(),
703                _old_heuristics->coalesce_and_fill_candidates_count());
704 }
705 
706 void ShenandoahOldGeneration::parallel_region_iterate_free(ShenandoahHeapRegionClosure* cl) {
707   // Iterate over old and free regions (exclude young).
708   ShenandoahExcludeRegionClosure<YOUNG_GENERATION> exclude_cl(cl);
709   ShenandoahGeneration::parallel_region_iterate_free(&exclude_cl);
710 }
711 
712 void ShenandoahOldGeneration::set_parseable(bool parseable) {
713   _is_parseable = parseable;
714   if (_is_parseable) {
715     // The current state would have been chosen during final mark of the global
716     // collection, _before_ any decisions about class unloading have been made.
717     //
718     // After unloading classes, we have made the old generation regions parseable.
719     // We can skip filling or transition to a state that knows everything has
720     // already been filled.
721     switch (state()) {
722       case ShenandoahOldGeneration::EVACUATING:
723         transition_to(ShenandoahOldGeneration::EVACUATING_AFTER_GLOBAL);
724         break;
725       case ShenandoahOldGeneration::FILLING:
726         assert(_old_heuristics->unprocessed_old_collection_candidates() == 0, "Expected no mixed collection candidates");
727         assert(_old_heuristics->coalesce_and_fill_candidates_count() > 0, "Expected coalesce and fill candidates");
728         // When the heuristic put the old generation in this state, it didn't know
729         // that we would unload classes and make everything parseable. But, we know
730         // that now so we can override this state.
731         // TODO: It would be nicer if we didn't have to 'correct' this situation.
732         abandon_collection_candidates();
733         transition_to(ShenandoahOldGeneration::WAITING_FOR_BOOTSTRAP);
734         break;
735       default:
736         // We can get here during a full GC. The full GC will cancel anything
737         // happening in the old generation and return it to the waiting for bootstrap
738         // state. The full GC will then record that the old regions are parseable
739         // after rebuilding the remembered set.
740         assert(is_idle(), "Unexpected state %s at end of global GC", state_name());
741         break;
742     }
743   }
744 }
745 
746 void ShenandoahOldGeneration::complete_mixed_evacuations() {
747   assert(is_doing_mixed_evacuations(), "Mixed evacuations should be in progress");
748   if (!_old_heuristics->has_coalesce_and_fill_candidates()) {
749     // No candidate regions to coalesce and fill
750     transition_to(ShenandoahOldGeneration::WAITING_FOR_BOOTSTRAP);
751     return;
752   }
753 
754   if (state() == ShenandoahOldGeneration::EVACUATING) {
755     transition_to(ShenandoahOldGeneration::FILLING);
756     return;
757   }
758 
759   // Here, we have no more candidates for mixed collections. The candidates for coalescing
760   // and filling have already been processed during the global cycle, so there is nothing
761   // more to do.
762   assert(state() == ShenandoahOldGeneration::EVACUATING_AFTER_GLOBAL, "Should be evacuating after a global cycle");
763   abandon_collection_candidates();
764   transition_to(ShenandoahOldGeneration::WAITING_FOR_BOOTSTRAP);
765 }
766 
767 void ShenandoahOldGeneration::abandon_mixed_evacuations() {
768   switch(state()) {
769     case ShenandoahOldGeneration::EVACUATING:
770       transition_to(ShenandoahOldGeneration::FILLING);
771       break;
772     case ShenandoahOldGeneration::EVACUATING_AFTER_GLOBAL:
773       abandon_collection_candidates();
774       transition_to(ShenandoahOldGeneration::WAITING_FOR_BOOTSTRAP);
775       break;
776     default:
777       ShouldNotReachHere();
778       break;
779   }
780 }
781 
782 void ShenandoahOldGeneration::clear_cards_for(ShenandoahHeapRegion* region) {
783   _card_scan->mark_range_as_empty(region->bottom(), pointer_delta(region->end(), region->bottom()));
784 }
785 
786 void ShenandoahOldGeneration::mark_card_as_dirty(void* location) {
787   _card_scan->mark_card_as_dirty((HeapWord*)location);
788 }