1 /*
   2  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   3  * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "gc/shenandoah/shenandoahAgeCensus.hpp"
  27 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  28 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  29 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
  30 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  31 #include "gc/shenandoah/shenandoahGeneration.hpp"
  32 #include "gc/shenandoah/shenandoahGenerationalControlThread.hpp"
  33 #include "gc/shenandoah/shenandoahGenerationalEvacuationTask.hpp"
  34 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp"
  35 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  36 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  37 #include "gc/shenandoah/shenandoahHeapRegionClosures.hpp"
  38 #include "gc/shenandoah/shenandoahInitLogger.hpp"
  39 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
  40 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  41 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
  42 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  43 #include "gc/shenandoah/shenandoahRegulatorThread.hpp"
  44 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
  45 #include "gc/shenandoah/shenandoahUtils.hpp"
  46 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  47 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  48 #include "logging/log.hpp"
  49 #include "utilities/events.hpp"
  50 
  51 
  52 class ShenandoahGenerationalInitLogger : public ShenandoahInitLogger {
  53 public:
  54   static void print() {
  55     ShenandoahGenerationalInitLogger logger;
  56     logger.print_all();
  57   }
  58 protected:
  59   void print_gc_specific() override {
  60     ShenandoahInitLogger::print_gc_specific();
  61 
  62     ShenandoahGenerationalHeap* heap = ShenandoahGenerationalHeap::heap();
  63     log_info(gc, init)("Young Heuristics: %s", heap->young_generation()->heuristics()->name());
  64     log_info(gc, init)("Old Heuristics: %s", heap->old_generation()->heuristics()->name());
  65   }
  66 };
  67 
  68 size_t ShenandoahGenerationalHeap::calculate_min_plab() {
  69   return PLAB::min_size();
  70 }
  71 
  72 size_t ShenandoahGenerationalHeap::calculate_max_plab() {
  73   return ShenandoahHeapRegion::max_tlab_size_words();
  74 }
  75 
  76 // Returns size in bytes
  77 size_t ShenandoahGenerationalHeap::unsafe_max_tlab_alloc() const {
  78   return MIN2(ShenandoahHeapRegion::max_tlab_size_bytes(), young_generation()->available());
  79 }
  80 
  81 ShenandoahGenerationalHeap::ShenandoahGenerationalHeap(ShenandoahCollectorPolicy* policy) :
  82   ShenandoahHeap(policy),
  83   _age_census(nullptr),
  84   _min_plab_size(calculate_min_plab()),
  85   _max_plab_size(calculate_max_plab()),
  86   _regulator_thread(nullptr),
  87   _young_gen_memory_pool(nullptr),
  88   _old_gen_memory_pool(nullptr) {
  89 }
  90 
  91 void ShenandoahGenerationalHeap::initialize_generations() {
  92   ShenandoahHeap::initialize_generations();
  93   _young_generation->post_initialize(this);
  94   _old_generation->post_initialize(this);
  95 }
  96 
  97 void ShenandoahGenerationalHeap::post_initialize() {
  98   ShenandoahHeap::post_initialize();
  99   _age_census = new ShenandoahAgeCensus();
 100 }
 101 
 102 void ShenandoahGenerationalHeap::post_initialize_heuristics() {
 103   ShenandoahHeap::post_initialize_heuristics();
 104   _young_generation->post_initialize_heuristics();
 105   _old_generation->post_initialize_heuristics();
 106 }
 107 
 108 void ShenandoahGenerationalHeap::print_init_logger() const {
 109   ShenandoahGenerationalInitLogger logger;
 110   logger.print_all();
 111 }
 112 
 113 void ShenandoahGenerationalHeap::initialize_heuristics() {
 114   // Initialize global generation and heuristics even in generational mode.
 115   ShenandoahHeap::initialize_heuristics();
 116 
 117   _young_generation = new ShenandoahYoungGeneration(max_workers());
 118   _old_generation = new ShenandoahOldGeneration(max_workers());
 119   _young_generation->initialize_heuristics(mode());
 120   _old_generation->initialize_heuristics(mode());
 121 }
 122 
 123 void ShenandoahGenerationalHeap::initialize_serviceability() {
 124   assert(mode()->is_generational(), "Only for the generational mode");
 125   _young_gen_memory_pool = new ShenandoahYoungGenMemoryPool(this);
 126   _old_gen_memory_pool = new ShenandoahOldGenMemoryPool(this);
 127   cycle_memory_manager()->add_pool(_young_gen_memory_pool);
 128   cycle_memory_manager()->add_pool(_old_gen_memory_pool);
 129   stw_memory_manager()->add_pool(_young_gen_memory_pool);
 130   stw_memory_manager()->add_pool(_old_gen_memory_pool);
 131 }
 132 
 133 GrowableArray<MemoryPool*> ShenandoahGenerationalHeap::memory_pools() {
 134   assert(mode()->is_generational(), "Only for the generational mode");
 135   GrowableArray<MemoryPool*> memory_pools(2);
 136   memory_pools.append(_young_gen_memory_pool);
 137   memory_pools.append(_old_gen_memory_pool);
 138   return memory_pools;
 139 }
 140 
 141 void ShenandoahGenerationalHeap::initialize_controller() {
 142   auto control_thread = new ShenandoahGenerationalControlThread();
 143   _control_thread = control_thread;
 144   _regulator_thread = new ShenandoahRegulatorThread(control_thread);
 145 }
 146 
 147 void ShenandoahGenerationalHeap::gc_threads_do(ThreadClosure* tcl) const {
 148   if (!shenandoah_policy()->is_at_shutdown()) {
 149     ShenandoahHeap::gc_threads_do(tcl);
 150     tcl->do_thread(regulator_thread());
 151   }
 152 }
 153 
 154 void ShenandoahGenerationalHeap::stop() {
 155   ShenandoahHeap::stop();
 156   regulator_thread()->stop();
 157 }
 158 
 159 void ShenandoahGenerationalHeap::start_idle_span() {
 160   young_generation()->heuristics()->start_idle_span();
 161 }
 162 
 163 bool ShenandoahGenerationalHeap::requires_barriers(stackChunkOop obj) const {
 164   if (ShenandoahHeap::requires_barriers(obj)) {
 165     return true;
 166   }
 167 
 168   if (is_concurrent_young_mark_in_progress() && is_in_young(obj) && !marking_context()->allocated_after_mark_start(obj)) {
 169     // We are marking young, this object is in young, and it is below the TAMS
 170     return true;
 171   }
 172 
 173   if (is_in_old(obj)) {
 174     // Card marking barriers are required for objects in the old generation
 175     return true;
 176   }
 177 
 178   return false;
 179 }
 180 
 181 void ShenandoahGenerationalHeap::evacuate_collection_set(ShenandoahGeneration* generation, bool concurrent) {
 182   ShenandoahRegionIterator regions;
 183   ShenandoahGenerationalEvacuationTask task(this, generation, &regions, concurrent, false /* only promote regions */);
 184   workers()->run_task(&task);
 185 }
 186 
 187 void ShenandoahGenerationalHeap::promote_regions_in_place(ShenandoahGeneration* generation, bool concurrent) {
 188   ShenandoahRegionIterator regions;
 189   ShenandoahGenerationalEvacuationTask task(this, generation, &regions, concurrent, true /* only promote regions */);
 190   workers()->run_task(&task);
 191 }
 192 
 193 oop ShenandoahGenerationalHeap::evacuate_object(oop p, Thread* thread) {
 194   assert(thread == Thread::current(), "Expected thread parameter to be current thread.");
 195 
 196   ShenandoahHeapRegion* from_region = heap_region_containing(p);
 197   assert(!from_region->is_humongous(), "never evacuate humongous objects");
 198 
 199   // Try to keep the object in the same generation
 200   const ShenandoahAffiliation target_gen = from_region->affiliation();
 201 
 202   if (target_gen == YOUNG_GENERATION) {
 203     markWord mark = p->mark();
 204     if (mark.is_marked()) {
 205       // Already forwarded.
 206       return ShenandoahForwarding::get_forwardee(p);
 207     }
 208 
 209     if (age_census()->is_tenurable(from_region->age() + mark.age())) {
 210       // If the object is tenurable, try to promote it
 211       oop result = try_evacuate_object<YOUNG_GENERATION, OLD_GENERATION>(p, thread, from_region->age());
 212 
 213       // If we failed to promote this aged object, we'll fall through to code below and evacuate to young-gen.
 214       if (result != nullptr) {
 215         return result;
 216       }
 217     }
 218     return try_evacuate_object<YOUNG_GENERATION, YOUNG_GENERATION>(p, thread, from_region->age());
 219   }
 220 
 221   assert(target_gen == OLD_GENERATION, "Expected evacuation to old");
 222   return try_evacuate_object<OLD_GENERATION, OLD_GENERATION>(p, thread, from_region->age());
 223 }
 224 
 225 // try_evacuate_object registers the object and dirties the associated remembered set information when evacuating
 226 // to OLD_GENERATION.
 227 template<ShenandoahAffiliation FROM_GENERATION, ShenandoahAffiliation TO_GENERATION>
 228 oop ShenandoahGenerationalHeap::try_evacuate_object(oop p, Thread* thread, uint from_region_age) {
 229   bool alloc_from_lab = true;
 230   bool has_plab = false;
 231   HeapWord* copy = nullptr;
 232   size_t size = ShenandoahForwarding::size(p);
 233   constexpr bool is_promotion = (TO_GENERATION == OLD_GENERATION) && (FROM_GENERATION == YOUNG_GENERATION);
 234 
 235 #ifdef ASSERT
 236   if (ShenandoahOOMDuringEvacALot &&
 237       (os::random() & 1) == 0) { // Simulate OOM every ~2nd slow-path call
 238     copy = nullptr;
 239   } else {
 240 #endif
 241     if (UseTLAB) {
 242       switch (TO_GENERATION) {
 243         case YOUNG_GENERATION: {
 244           copy = allocate_from_gclab(thread, size);
 245           if ((copy == nullptr) && (size < ShenandoahThreadLocalData::gclab_size(thread))) {
 246             // GCLAB allocation failed because we are bumping up against the limit on young evacuation reserve.  Try resetting
 247             // the desired GCLAB size and retry GCLAB allocation to avoid cascading of shared memory allocations.
 248             ShenandoahThreadLocalData::set_gclab_size(thread, PLAB::min_size());
 249             copy = allocate_from_gclab(thread, size);
 250             // If we still get nullptr, we'll try a shared allocation below.
 251           }
 252           break;
 253         }
 254         case OLD_GENERATION: {
 255           ShenandoahPLAB* shenandoah_plab = ShenandoahThreadLocalData::shenandoah_plab(thread);
 256           if (shenandoah_plab != nullptr) {
 257             has_plab = true;
 258             copy = shenandoah_plab->allocate(size, is_promotion);
 259             if (copy == nullptr && size < shenandoah_plab->desired_size() && shenandoah_plab->retries_enabled()) {
 260               // PLAB allocation failed because we are bumping up against the limit on old evacuation reserve or because
 261               // the requested object does not fit within the current plab but the plab still has an "abundance" of memory,
 262               // where abundance is defined as >= ShenGenHeap::plab_min_size().  In the former case, we try shrinking the
 263               // desired PLAB size to the minimum and retry PLAB allocation to avoid cascading of shared memory allocations.
 264               // Shrinking the desired PLAB size may allow us to eke out a small PLAB while staying beneath evacuation reserve.
 265               if (shenandoah_plab->plab()->words_remaining() < plab_min_size()) {
 266                 shenandoah_plab->set_desired_size(plab_min_size());
 267                 copy = shenandoah_plab->allocate(size, is_promotion);
 268                 if (copy == nullptr) {
 269                   // If we still get nullptr, we'll try a shared allocation below.
 270                   // However, don't continue to retry until we have success (probably in next GC pass)
 271                   shenandoah_plab->disable_retries();
 272                 }
 273               }
 274             }
 275           }
 276           break;
 277         }
 278         default: {
 279           ShouldNotReachHere();
 280           break;
 281         }
 282       }
 283     }
 284 
 285     if (copy == nullptr) {
 286       // If we failed to allocate in LAB, we'll try a shared allocation.
 287       if (!is_promotion || !has_plab || (size > PLAB::min_size())) {
 288         ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared_gc(size, TO_GENERATION, is_promotion);
 289         copy = allocate_memory(req);
 290         alloc_from_lab = false;
 291       }
 292       // else, we leave copy equal to nullptr, signaling a promotion failure below if appropriate.
 293       // We choose not to promote objects smaller than size_threshold by way of shared allocations as this is too
 294       // costly.  Instead, we'll simply "evacuate" to young-gen memory (using a GCLAB) and will promote in a future
 295       // evacuation pass.  This condition is denoted by: is_promotion && has_plab && (size <= size_threshhold).
 296     }
 297 #ifdef ASSERT
 298   }
 299 #endif
 300 
 301   if (copy == nullptr) {
 302     if (TO_GENERATION == OLD_GENERATION) {
 303       if (FROM_GENERATION == YOUNG_GENERATION) {
 304         // Signal that promotion failed. Will evacuate this old object somewhere in young gen.
 305         old_generation()->handle_failed_promotion(thread, size);
 306         return nullptr;
 307       } else {
 308         // Remember that evacuation to old gen failed. We'll want to trigger a full gc to recover from this
 309         // after the evacuation threads have finished.
 310         old_generation()->handle_failed_evacuation();
 311       }
 312     }
 313 
 314     control_thread()->handle_alloc_failure_evac(size);
 315 
 316     // Install the self-forwarded bit so other evacuators/LRBs see the
 317     // object as "already handled, do not try to evacuate". The CAS may
 318     // fail if another thread concurrently installed a real forwardee or
 319     // self-forwarded first.
 320     markWord old_mark = p->mark();
 321     if (old_mark.is_forwarded()) {
 322       return ShenandoahForwarding::get_forwardee(p);
 323     }
 324     oop winner = ShenandoahForwarding::try_forward_to_self(p, old_mark);
 325     if (winner == nullptr) {
 326       // We own the self-forwarding. Flag the from-region so the degen/full
 327       // GC entry drain knows to scan it for self_fwd bits to clear.
 328       heap_region_containing(p)->set_has_self_forwards();
 329       return p;
 330     }
 331     return winner;
 332   }
 333 
 334   if (ShenandoahEvacTracking) {
 335     evac_tracker()->begin_evacuation(thread, size * HeapWordSize, FROM_GENERATION, TO_GENERATION);
 336   }
 337 
 338   // Copy the object:
 339   Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(p), copy, size);
 340   oop copy_val = cast_to_oop(copy);
 341 
 342   // Update the age of the evacuated object
 343   if (TO_GENERATION == YOUNG_GENERATION) {
 344     increase_object_age(copy_val, from_region_age + 1);
 345   }
 346 
 347   // Relativize stack chunks before publishing the copy. After the forwarding CAS,
 348   // mutators can see the copy and thaw it via the fast path if flags == 0. We must
 349   // relativize derived pointers and set gc_mode before that happens. Skip if the
 350   // copy's mark word is already a forwarding pointer (another thread won the race
 351   // and overwrote the original's header before we copied it).
 352   if (!ShenandoahForwarding::is_forwarded(copy_val)) {
 353     ContinuationGCSupport::relativize_stack_chunk(copy_val);
 354   }
 355 
 356   // Try to install the new forwarding pointer.
 357   oop result = ShenandoahForwarding::try_update_forwardee(p, copy_val);
 358   if (result == copy_val) {
 359     // Successfully evacuated. Our copy is now the public one!
 360     if (ShenandoahEvacTracking) {
 361       // Record that the evacuation succeeded
 362       evac_tracker()->end_evacuation(thread, size * HeapWordSize, FROM_GENERATION, TO_GENERATION);
 363     }
 364   }  else {
 365     // Failed to evacuate. We need to deal with the object that is left behind. Since this
 366     // new allocation is certainly after TAMS, it will be considered live in the next cycle.
 367     // But if it happens to contain references to evacuated regions, those references would
 368     // not get updated for this stale copy during this cycle, and we will crash while scanning
 369     // it the next cycle.
 370     if (alloc_from_lab) {
 371       // For LAB allocations, it is enough to rollback the allocation ptr. Either the next
 372       // object will overwrite this stale copy, or the filler object on LAB retirement will
 373       // do this.
 374       switch (TO_GENERATION) {
 375         case YOUNG_GENERATION: {
 376           ShenandoahThreadLocalData::gclab(thread)->undo_allocation(copy, size);
 377           break;
 378         }
 379         case OLD_GENERATION: {
 380           ShenandoahThreadLocalData::shenandoah_plab(thread)->plab()->undo_allocation(copy, size);
 381           if (is_promotion) {
 382             ShenandoahThreadLocalData::shenandoah_plab(thread)->subtract_from_promoted(size * HeapWordSize);
 383           }
 384           break;
 385         }
 386         default: {
 387           ShouldNotReachHere();
 388           break;
 389         }
 390       }
 391     } else {
 392       // For non-LAB allocations, we have no way to retract the allocation, and
 393       // have to explicitly overwrite the copy with the filler object. With that overwrite,
 394       // we have to keep the fwdptr initialized and pointing to our (stale) copy.
 395       assert(size >= ShenandoahHeap::min_fill_size(), "previously allocated object known to be larger than min_size");
 396       fill_with_object(copy, size);
 397     }
 398   }
 399   shenandoah_assert_correct(nullptr, result);
 400   return result;
 401 }
 402 
 403 template oop ShenandoahGenerationalHeap::try_evacuate_object<YOUNG_GENERATION, YOUNG_GENERATION>(oop p, Thread* thread, uint from_region_age);
 404 template oop ShenandoahGenerationalHeap::try_evacuate_object<YOUNG_GENERATION, OLD_GENERATION>(oop p, Thread* thread, uint from_region_age);
 405 template oop ShenandoahGenerationalHeap::try_evacuate_object<OLD_GENERATION, OLD_GENERATION>(oop p, Thread* thread, uint from_region_age);
 406 
 407 // Call this function at the end of a GC cycle in order to establish proper sizes of young and old reserves,
 408 // setting the old-generation balance so that GC can perform the anticipated evacuations.
 409 //
 410 // Make sure old-generation is large enough, but no larger than is necessary, to hold mixed evacuations
 411 // and promotions, if we anticipate either. Any deficit is provided by the young generation, subject to
 412 // mutator_xfer_limit, and any surplus is transferred to the young generation.  mutator_xfer_limit is
 413 // the maximum we're able to transfer from young to old. The mutator_xfer_limit constrains the transfer
 414 // of memory from young to old.  It does not limit young reserves.
 415 void ShenandoahGenerationalHeap::compute_old_generation_balance(size_t mutator_xfer_limit,
 416                                                                 size_t old_trashed_regions, size_t young_trashed_regions) {
 417   shenandoah_assert_heaplocked();
 418   // We can limit the old reserve to the size of anticipated promotions:
 419   // max_old_reserve is an upper bound on memory evacuated from old and promoted to old,
 420   // clamped by the old generation space available.
 421   //
 422   // Here's the algebra.
 423   // Let SOEP = ShenandoahOldEvacPercent,
 424   //     OE = old evac,
 425   //     YE = young evac, and
 426   //     TE = total evac = OE + YE
 427   // By definition:
 428   //            SOEP/100 = OE/TE
 429   //                     = OE/(OE+YE)
 430   //  => SOEP/(100-SOEP) = OE/((OE+YE)-OE)      // componendo-dividendo: If a/b = c/d, then a/(b-a) = c/(d-c)
 431   //                     = OE/YE
 432   //  =>              OE = YE*SOEP/(100-SOEP)
 433 
 434   // We have to be careful in the event that SOEP is set to 100 by the user.
 435   assert(ShenandoahOldEvacPercent <= 100, "Error");
 436   const size_t region_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 437 
 438   ShenandoahOldGeneration* old_gen = old_generation();
 439   size_t old_capacity = old_gen->max_capacity();
 440   size_t old_usage = old_gen->used(); // includes humongous waste
 441   size_t old_currently_available =
 442     ((old_capacity >= old_usage)? old_capacity - old_usage: 0) + old_trashed_regions * region_size_bytes;
 443 
 444   ShenandoahYoungGeneration* young_gen = young_generation();
 445   size_t young_capacity = young_gen->max_capacity();
 446   size_t young_usage = young_gen->used(); // includes humongous waste
 447   size_t young_available = ((young_capacity >= young_usage)? young_capacity - young_usage: 0);
 448   size_t freeset_available = free_set()->available_locked();
 449   if (young_available > freeset_available) {
 450     young_available = freeset_available;
 451   }
 452   young_available += young_trashed_regions * region_size_bytes;
 453 
 454   // The free set will reserve this amount of memory to hold young evacuations (initialized to the ideal reserve)
 455   size_t young_reserve = (young_generation()->max_capacity() * ShenandoahEvacReserve) / 100;
 456 
 457   // If ShenandoahOldEvacPercent equals 100, max_old_reserve is limited only by mutator_xfer_limit and young_reserve
 458   const size_t bound_on_old_reserve =
 459     ((old_currently_available + mutator_xfer_limit + young_reserve) * ShenandoahOldEvacPercent) / 100;
 460   size_t proposed_max_old = ((ShenandoahOldEvacPercent == 100)?
 461                              bound_on_old_reserve:
 462                              MIN2((young_reserve * ShenandoahOldEvacPercent) / (100 - ShenandoahOldEvacPercent),
 463                                   bound_on_old_reserve));
 464   assert(mutator_xfer_limit <= young_available,
 465          "Cannot transfer (%zu) memory that is not available (%zu)", mutator_xfer_limit, young_available);
 466 
 467   if (young_reserve > young_available) {
 468     young_reserve = young_available;
 469   }
 470   // We allow young_reserve to exceed mutator_xfer_limit. Essentially, this means the GC is already behind the pace
 471   // of mutator allocations, and we'll need to trigger the next GC as soon as possible.
 472   if (mutator_xfer_limit > young_reserve) {
 473     mutator_xfer_limit -= young_reserve;
 474   } else {
 475     mutator_xfer_limit = 0;
 476   }
 477 
 478   // Decide how much old space we should reserve for a mixed collection
 479   size_t proposed_reserve_for_mixed = 0;
 480   const size_t old_fragmented_available =
 481     old_currently_available - (old_generation()->free_unaffiliated_regions() + old_trashed_regions) * region_size_bytes;
 482 
 483   if (old_fragmented_available > proposed_max_old) {
 484     // In this case, the old_fragmented_available is greater than the desired amount of evacuation to old.
 485     // We'll use all of this memory to hold results of old evacuation, and we'll give back to the young generation
 486     // any old regions that are not fragmented.
 487     //
 488     // This scenario may happen after we have promoted many regions in place, and each of these regions had non-zero
 489     // unused memory, so there is now an abundance of old-fragmented available memory, even more than the desired
 490     // percentage for old reserve.  We cannot transfer these fragmented regions back to young.  Instead we make the
 491     // best of the situation by using this fragmented memory for both promotions and evacuations.
 492 
 493     proposed_max_old = old_fragmented_available;
 494   }
 495   // Otherwise: old_fragmented_available <= proposed_max_old. Do not shrink proposed_max_old from the original computation.
 496 
 497   // Though we initially set proposed_reserve_for_promo to equal the entirety of old fragmented available, we have the
 498   // opportunity below to shift some of this memory into the proposed_reserve_for_mixed.
 499   size_t proposed_reserve_for_promo = old_fragmented_available;
 500   const size_t max_old_reserve = proposed_max_old;
 501 
 502   const size_t mixed_candidate_live_memory = old_generation()->unprocessed_collection_candidates_live_memory();
 503   const bool doing_mixed = (mixed_candidate_live_memory > 0);
 504   if (doing_mixed) {
 505     // In the ideal, all of the memory reserved for mixed evacuation would be unfragmented, but we don't enforce
 506     // this.  Note that the initial value of  max_evac_need is conservative because we may not evacuate all of the
 507     // remaining mixed evacuation candidates in a single cycle.
 508     const size_t max_evac_need = (size_t) (mixed_candidate_live_memory * ShenandoahOldEvacWaste);
 509     assert(old_currently_available >= old_generation()->free_unaffiliated_regions() * region_size_bytes,
 510            "Unaffiliated available must be less than total available");
 511 
 512     // We prefer to evacuate all of mixed into unfragmented memory, and will expand old in order to do so, unless
 513     // we already have too much fragmented available memory in old.
 514     proposed_reserve_for_mixed = max_evac_need;
 515     if (proposed_reserve_for_mixed + proposed_reserve_for_promo > max_old_reserve) {
 516       // We're trying to reserve more memory than is available.  So we need to shrink our reserves.
 517       size_t excess_reserves = (proposed_reserve_for_mixed + proposed_reserve_for_promo) - max_old_reserve;
 518       // We need to shrink reserves by excess_reserves.  We prefer to shrink by reducing promotion, giving priority to mixed
 519       // evacuation.  If the promotion reserve is larger than the amount we need to shrink by, do all the shrinkage there.
 520       if (proposed_reserve_for_promo > excess_reserves) {
 521         proposed_reserve_for_promo -= excess_reserves;
 522       } else {
 523         // Otherwise, we'll shrink promotion reserve to zero and we'll shrink the mixed-evac reserve by the remaining excess.
 524         excess_reserves -= proposed_reserve_for_promo;
 525         proposed_reserve_for_promo = 0;
 526         proposed_reserve_for_mixed -= excess_reserves;
 527       }
 528     }
 529   }
 530   assert(proposed_reserve_for_mixed + proposed_reserve_for_promo <= max_old_reserve,
 531          "Reserve for mixed (%zu) plus reserve for promotions (%zu) must be less than maximum old reserve (%zu)",
 532          proposed_reserve_for_mixed, proposed_reserve_for_promo, max_old_reserve);
 533 
 534   // Decide how much additional space we should reserve for promotions from young.  We give priority to mixed evacations
 535   // over promotions.
 536   const size_t promo_load = old_generation()->get_promotion_potential();
 537   const bool doing_promotions = promo_load > 0;
 538 
 539   // promo_load represents the combined total of live memory within regions that have reached tenure age.  The true
 540   // promotion potential is larger than this, because individual objects within regions that have not yet reached tenure
 541   // age may be promotable. On the other hand, some of the objects that we intend to promote in the next GC cycle may
 542   // die before they are next marked.  In the future, the promo_load will include the total size of tenurable objects
 543   // residing in regions that have not yet reached tenure age.
 544 
 545   if (doing_promotions) {
 546     // We are always doing promotions, even when old_generation->get_promotion_potential() returns 0.  As currently implemented,
 547     // get_promotion_potential() only knows the total live memory contained within young-generation regions whose age is
 548     // tenurable. It does not know whether that memory will still be live at the end of the next mark cycle, and it doesn't
 549     // know how much memory is contained within objects whose individual ages are tenurable, which reside in regions with
 550     // non-tenurable age.  We use this, as adjusted by ShenandoahPromoEvacWaste, as an approximation of the total amount of
 551     // memory to be promoted.  In the near future, we expect to implement a change that will allow get_promotion_potential()
 552     // to account also for the total memory contained within individual objects that are tenure-ready even when they do
 553     // not reside in aged regions.  This will represent a conservative over approximation of promotable memory because
 554     // some of these objects may die before the next GC cycle executes.
 555 
 556     // Be careful not to ask for too much promotion reserves. We have observed jtreg test failures under which a greedy
 557     // promotion reserve causes a humongous allocation which is awaiting a full GC to fail (specifically
 558     // gc/TestAllocHumongousFragment.java). This happens if too much of the memory reclaimed by the full GC
 559     // is immediately reserved so that it cannot be allocated by the waiting mutator. It's not clear that this
 560     // particular test is representative of the needs of typical GenShen users.  It is really a test of high frequency
 561     // Full GCs under heap fragmentation stress.
 562 
 563     size_t promo_need = (size_t) (promo_load * ShenandoahPromoEvacWaste);
 564     if (promo_need > proposed_reserve_for_promo) {
 565       const size_t available_for_additional_promotions =
 566         max_old_reserve - (proposed_reserve_for_mixed + proposed_reserve_for_promo);
 567       if (proposed_reserve_for_promo + available_for_additional_promotions >= promo_need) {
 568         proposed_reserve_for_promo = promo_need;
 569       } else {
 570         proposed_reserve_for_promo += available_for_additional_promotions;
 571       }
 572     }
 573   }
 574   // else, leave proposed_reserve_for_promo as is.  By default, it is initialized to represent old_fragmented_available.
 575 
 576   // This is the total old we want to reserve (initialized to the ideal reserve)
 577   size_t proposed_old_reserve = proposed_reserve_for_mixed + proposed_reserve_for_promo;
 578 
 579   // We now check if the old generation is running a surplus or a deficit.
 580   size_t old_region_deficit = 0;
 581   size_t old_region_surplus = 0;
 582 
 583   size_t mutator_region_xfer_limit = mutator_xfer_limit / region_size_bytes;
 584   // align the mutator_xfer_limit on region size
 585   mutator_xfer_limit = mutator_region_xfer_limit * region_size_bytes;
 586 
 587   if (old_currently_available >= proposed_old_reserve) {
 588     // We are running a surplus, so the old region surplus can go to young
 589     const size_t old_surplus = old_currently_available - proposed_old_reserve;
 590     old_region_surplus = old_surplus / region_size_bytes;
 591     const size_t unaffiliated_old_regions = old_generation()->free_unaffiliated_regions() + old_trashed_regions;
 592     old_region_surplus = MIN2(old_region_surplus, unaffiliated_old_regions);
 593     old_generation()->set_region_balance(checked_cast<ssize_t>(old_region_surplus));
 594     old_currently_available -= old_region_surplus * region_size_bytes;
 595     young_available += old_region_surplus * region_size_bytes;
 596   } else if (old_currently_available + mutator_xfer_limit >= proposed_old_reserve) {
 597     // We know that old_currently_available < proposed_old_reserve because above test failed. Expand old_currently_available.
 598     // Mutator's xfer limit is sufficient to satisfy our need: transfer all memory from there.
 599     size_t old_deficit = proposed_old_reserve - old_currently_available;
 600     old_region_deficit = (old_deficit + region_size_bytes - 1) / region_size_bytes;
 601     old_generation()->set_region_balance(0 - checked_cast<ssize_t>(old_region_deficit));
 602     old_currently_available += old_region_deficit * region_size_bytes;
 603     young_available -= old_region_deficit * region_size_bytes;
 604   } else {
 605     // We know that (old_currently_available < proposed_old_reserve) and
 606     //   (old_currently_available + mutator_xfer_limit < proposed_old_reserve) because above tests failed.
 607     // We need to shrink proposed_old_reserves.
 608 
 609     // We could potentially shrink young_reserves in order to further expand proposed_old_reserves.  Let's not bother.  The
 610     // important thing is that we keep a total amount of memory in reserve in preparation for the next GC cycle.  At
 611     // the time we choose the next collection set, we'll have an opportunity to shift some of these young reserves
 612     // into old reserves if that makes sense.
 613 
 614     // Start by taking all of mutator_xfer_limit into old_currently_available.
 615     size_t old_region_deficit = mutator_region_xfer_limit;
 616     old_generation()->set_region_balance(0 - checked_cast<ssize_t>(old_region_deficit));
 617     old_currently_available += old_region_deficit * region_size_bytes;
 618     young_available -= old_region_deficit * region_size_bytes;
 619 
 620     assert(old_currently_available < proposed_old_reserve,
 621            "Old currently available (%zu) must be less than old reserve (%zu)", old_currently_available, proposed_old_reserve);
 622 
 623     // There's not enough memory to satisfy our desire.  Scale back our old-gen intentions.  We prefer to satisfy
 624     // the budget_overrun entirely from the promotion reserve, if that is large enough.  Otherwise, we'll satisfy
 625     // the overrun from a combination of promotion and mixed-evacuation reserves.
 626     size_t budget_overrun = proposed_old_reserve - old_currently_available;
 627     if (proposed_reserve_for_promo > budget_overrun) {
 628       proposed_reserve_for_promo -= budget_overrun;
 629       // Dead code:
 630       //  proposed_old_reserve -= budget_overrun;
 631     } else {
 632       budget_overrun -= proposed_reserve_for_promo;
 633       proposed_reserve_for_promo = 0;
 634       proposed_reserve_for_mixed = (proposed_reserve_for_mixed > budget_overrun)? proposed_reserve_for_mixed - budget_overrun: 0;
 635       // Dead code:
 636       //  Note: proposed_reserve_for_promo is 0 and proposed_reserve_for_mixed may equal 0.
 637       //  proposed_old_reserve = proposed_reserve_for_mixed;
 638     }
 639   }
 640 
 641   assert(old_region_deficit == 0 || old_region_surplus == 0,
 642          "Only surplus (%zu) or deficit (%zu), never both", old_region_surplus, old_region_deficit);
 643   assert(young_reserve + proposed_reserve_for_mixed + proposed_reserve_for_promo <= old_currently_available + young_available,
 644          "Cannot reserve more memory than is available: %zu + %zu + %zu <= %zu + %zu",
 645          young_reserve, proposed_reserve_for_mixed, proposed_reserve_for_promo, old_currently_available, young_available);
 646 
 647   // deficit/surplus adjustments to generation sizes will precede rebuild
 648   young_generation()->set_evacuation_reserve(young_reserve);
 649   old_generation()->set_evacuation_reserve(proposed_reserve_for_mixed);
 650   old_generation()->set_promoted_reserve(proposed_reserve_for_promo);
 651 }
 652 
 653 void ShenandoahGenerationalHeap::coalesce_and_fill_old_regions(bool concurrent) {
 654   class ShenandoahGlobalCoalesceAndFill : public WorkerTask {
 655   private:
 656       ShenandoahPhaseTimings::Phase _phase;
 657       ShenandoahRegionIterator _regions;
 658   public:
 659     explicit ShenandoahGlobalCoalesceAndFill(ShenandoahPhaseTimings::Phase phase) :
 660       WorkerTask("Shenandoah Global Coalesce"),
 661       _phase(phase) {}
 662 
 663     void work(uint worker_id) override {
 664       ShenandoahWorkerTimingsTracker timer(_phase,
 665                                            ShenandoahPhaseTimings::Work,
 666                                            worker_id, true);
 667       ShenandoahHeapRegion* region;
 668       while ((region = _regions.next()) != nullptr) {
 669         // old region is not in the collection set and was not immediately trashed
 670         if (region->is_old() && region->is_active() && !region->is_humongous()) {
 671           // Reset the coalesce and fill boundary because this is a global collect
 672           // and cannot be preempted by young collects. We want to be sure the entire
 673           // region is coalesced here and does not resume from a previously interrupted
 674           // or completed coalescing.
 675           region->begin_preemptible_coalesce_and_fill();
 676           region->oop_coalesce_and_fill(false);
 677         }
 678       }
 679     }
 680   };
 681 
 682   ShenandoahPhaseTimings::Phase phase = concurrent ?
 683           ShenandoahPhaseTimings::conc_coalesce_and_fill :
 684           ShenandoahPhaseTimings::degen_gc_coalesce_and_fill;
 685 
 686   // This is not cancellable
 687   ShenandoahGlobalCoalesceAndFill coalesce(phase);
 688   workers()->run_task(&coalesce);
 689   old_generation()->set_parsable(true);
 690 }
 691 
 692 template<bool CONCURRENT>
 693 class ShenandoahGenerationalUpdateHeapRefsTask : public WorkerTask {
 694 private:
 695   // For update refs, _generation will be young or global. Mixed collections use the young generation.
 696   ShenandoahGeneration* _generation;
 697   ShenandoahGenerationalHeap* _heap;
 698   ShenandoahRegionIterator* _regions;
 699   ShenandoahRegionChunkIterator* _work_chunks;
 700 
 701 public:
 702   ShenandoahGenerationalUpdateHeapRefsTask(ShenandoahGeneration* generation,
 703                                            ShenandoahRegionIterator* regions,
 704                                            ShenandoahRegionChunkIterator* work_chunks) :
 705           WorkerTask("Shenandoah Update References"),
 706           _generation(generation),
 707           _heap(ShenandoahGenerationalHeap::heap()),
 708           _regions(regions),
 709           _work_chunks(work_chunks)
 710   {
 711     const bool old_bitmap_stable = _heap->old_generation()->is_mark_complete();
 712     log_debug(gc, remset)("Update refs, scan remembered set using bitmap: %s", BOOL_TO_STR(old_bitmap_stable));
 713   }
 714 
 715   void work(uint worker_id) override {
 716     if (CONCURRENT) {
 717       ShenandoahWorkerTimingsTracker timer(ShenandoahPhaseTimings::conc_update_refs, ShenandoahPhaseTimings::Work, worker_id, true);
 718       ShenandoahConcurrentWorkerSession worker_session(worker_id);
 719       SuspendibleThreadSetJoiner stsj;
 720       do_work<ShenandoahConcUpdateRefsClosure>(worker_id);
 721     } else {
 722       ShenandoahWorkerTimingsTracker timer(ShenandoahPhaseTimings::degen_gc_update_refs, ShenandoahPhaseTimings::Work, worker_id, true);
 723       ShenandoahParallelWorkerSession worker_session(worker_id);
 724       do_work<ShenandoahNonConcUpdateRefsClosure>(worker_id);
 725     }
 726   }
 727 
 728 private:
 729   template<class T>
 730   void do_work(uint worker_id) {
 731     T cl;
 732 
 733     if (CONCURRENT && (worker_id == 0)) {
 734       // We ask the first worker to replenish the Mutator free set by moving regions previously reserved to hold the
 735       // results of evacuation.  These reserves are no longer necessary because evacuation has completed.
 736       size_t cset_regions = _heap->collection_set()->count();
 737 
 738       // Now that evacuation is done, we can reassign any regions that had been reserved to hold the results of evacuation
 739       // to the mutator free set.  At the end of GC, we will have cset_regions newly evacuated fully empty regions from
 740       // which we will be able to replenish the Collector free set and the OldCollector free set in preparation for the
 741       // next GC cycle.
 742       _heap->free_set()->move_regions_from_collector_to_mutator(cset_regions);
 743     }
 744     // If !CONCURRENT, there's no value in expanding Mutator free set
 745 
 746     ShenandoahHeapRegion* r = _regions->next();
 747     // We update references for global, mixed, and young collections.
 748     assert(_generation->is_mark_complete(), "Expected complete marking");
 749     ShenandoahMarkingContext* const ctx = _heap->marking_context();
 750     bool is_mixed = _heap->collection_set()->has_old_regions();
 751     while (r != nullptr) {
 752       HeapWord* update_watermark = r->get_update_watermark();
 753       assert(update_watermark >= r->bottom(), "sanity");
 754 
 755       log_debug(gc)("Update refs worker " UINT32_FORMAT ", looking at region %zu", worker_id, r->index());
 756       if (r->is_active() && !r->is_cset()) {
 757         if (r->is_young()) {
 758           _heap->marked_object_oop_iterate(r, &cl, update_watermark);
 759         } else if (r->is_old()) {
 760           if (_generation->is_global()) {
 761 
 762             _heap->marked_object_oop_iterate(r, &cl, update_watermark);
 763           }
 764           // Otherwise, this is an old region in a young or mixed cycle.  Process it during a second phase, below.
 765         } else {
 766           // Because updating of references runs concurrently, it is possible that a FREE inactive region transitions
 767           // to a non-free active region while this loop is executing.  Whenever this happens, the changing of a region's
 768           // active status may propagate at a different speed than the changing of the region's affiliation.
 769 
 770           // When we reach this control point, it is because a race has allowed a region's is_active() status to be seen
 771           // by this thread before the region's affiliation() is seen by this thread.
 772 
 773           // It's ok for this race to occur because the newly transformed region does not have any references to be
 774           // updated.
 775 
 776           assert(r->get_update_watermark() == r->bottom(),
 777                  "%s Region %zu is_active but not recognized as YOUNG or OLD so must be newly transitioned from FREE",
 778                  r->affiliation_name(), r->index());
 779         }
 780       }
 781 
 782       if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
 783         return;
 784       }
 785 
 786       r = _regions->next();
 787     }
 788 
 789     if (_generation->is_young()) {
 790       // Since this is generational and not GLOBAL, we have to process the remembered set.  There's no remembered
 791       // set processing if not in generational mode or if GLOBAL mode.
 792 
 793       // After this thread has exhausted its traditional update-refs work, it continues with updating refs within
 794       // remembered set. The remembered set workload is better balanced between threads, so threads that are "behind"
 795       // can catch up with other threads during this phase, allowing all threads to work more effectively in parallel.
 796       update_references_in_remembered_set(worker_id, cl, ctx, is_mixed);
 797     }
 798   }
 799 
 800   template<class T>
 801   void update_references_in_remembered_set(uint worker_id, T &cl, const ShenandoahMarkingContext* ctx, bool is_mixed) {
 802 
 803     struct ShenandoahRegionChunk assignment;
 804     ShenandoahScanRemembered* scanner = _heap->old_generation()->card_scan();
 805 
 806     while (!_heap->check_cancelled_gc_and_yield(CONCURRENT) && _work_chunks->next(&assignment)) {
 807       // Keep grabbing next work chunk to process until finished, or asked to yield
 808       ShenandoahHeapRegion* r = assignment._r;
 809       if (r->is_active() && !r->is_cset() && r->is_old()) {
 810         HeapWord* start_of_range = r->bottom() + assignment._chunk_offset;
 811         HeapWord* end_of_range = r->get_update_watermark();
 812         if (end_of_range > start_of_range + assignment._chunk_size) {
 813           end_of_range = start_of_range + assignment._chunk_size;
 814         }
 815 
 816         if (start_of_range >= end_of_range) {
 817           continue;
 818         }
 819 
 820         // Old region in a young cycle or mixed cycle.
 821         if (is_mixed) {
 822           if (r->is_humongous()) {
 823             // Need to examine both dirty and clean cards during mixed evac.
 824             r->oop_iterate_humongous_slice_all(&cl,start_of_range, assignment._chunk_size);
 825           } else {
 826             // Since this is mixed evacuation, old regions that are candidates for collection have not been coalesced
 827             // and filled.  This will use mark bits to find objects that need to be updated.
 828             update_references_in_old_region(cl, ctx, scanner, r, start_of_range, end_of_range);
 829           }
 830         } else {
 831           // This is a young evacuation
 832           size_t cluster_size = CardTable::card_size_in_words() * ShenandoahCardCluster::CardsPerCluster;
 833           size_t clusters = assignment._chunk_size / cluster_size;
 834           assert(clusters * cluster_size == assignment._chunk_size, "Chunk assignment must align on cluster boundaries");
 835           scanner->process_region_slice(r, assignment._chunk_offset, clusters, end_of_range, &cl, true, worker_id);
 836         }
 837       }
 838     }
 839   }
 840 
 841   template<class T>
 842   void update_references_in_old_region(T &cl, const ShenandoahMarkingContext* ctx, ShenandoahScanRemembered* scanner,
 843                                     const ShenandoahHeapRegion* r, HeapWord* start_of_range,
 844                                     HeapWord* end_of_range) const {
 845     // In case last object in my range spans boundary of my chunk, I may need to scan all the way to top()
 846     ShenandoahObjectToOopBoundedClosure<T> objs(&cl, start_of_range, r->top());
 847 
 848     // Any object that begins in a previous range is part of a different scanning assignment.  Any object that
 849     // starts after end_of_range is also not my responsibility.  (Either allocated during evacuation, so does
 850     // not hold pointers to from-space, or is beyond the range of my assigned work chunk.)
 851 
 852     // Find the first object that begins in my range, if there is one. Note that `p` will be set to `end_of_range`
 853     // when no live object is found in the range.
 854     HeapWord* tams = ctx->top_at_mark_start(r);
 855     HeapWord* p = get_first_object_start_word(ctx, scanner, tams, start_of_range, end_of_range);
 856 
 857     while (p < end_of_range) {
 858       // p is known to point to the beginning of marked object obj
 859       oop obj = cast_to_oop(p);
 860       objs.do_object(obj);
 861       HeapWord* prev_p = p;
 862       p += obj->size();
 863       if (p < tams) {
 864         p = ctx->get_next_marked_addr(p, tams);
 865         // If there are no more marked objects before tams, this returns tams.  Note that tams is
 866         // either >= end_of_range, or tams is the start of an object that is marked.
 867       }
 868       assert(p != prev_p, "Lack of forward progress");
 869     }
 870   }
 871 
 872   HeapWord* get_first_object_start_word(const ShenandoahMarkingContext* ctx, ShenandoahScanRemembered* scanner, HeapWord* tams,
 873                                         HeapWord* start_of_range, HeapWord* end_of_range) const {
 874     HeapWord* p = start_of_range;
 875 
 876     if (p >= tams) {
 877       // We cannot use ctx->is_marked(obj) to test whether an object begins at this address.  Instead,
 878       // we need to use the remembered set crossing map to advance p to the first object that starts
 879       // within the enclosing card.
 880       size_t card_index = scanner->card_index_for_addr(start_of_range);
 881       while (true) {
 882         HeapWord* first_object = scanner->first_object_in_card(card_index);
 883         if (first_object != nullptr) {
 884           p = first_object;
 885           break;
 886         } else if (scanner->addr_for_card_index(card_index + 1) < end_of_range) {
 887           card_index++;
 888         } else {
 889           // Signal that no object was found in range
 890           p = end_of_range;
 891           break;
 892         }
 893       }
 894     } else if (!ctx->is_marked(cast_to_oop(p))) {
 895       p = ctx->get_next_marked_addr(p, tams);
 896       // If there are no more marked objects before tams, this returns tams.
 897       // Note that tams is either >= end_of_range, or tams is the start of an object that is marked.
 898     }
 899     return p;
 900   }
 901 };
 902 
 903 void ShenandoahGenerationalHeap::update_heap_references(ShenandoahGeneration* generation, bool concurrent) {
 904   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
 905   const uint nworkers = workers()->active_workers();
 906   ShenandoahRegionChunkIterator work_list(nworkers);
 907   if (concurrent) {
 908     ShenandoahGenerationalUpdateHeapRefsTask<true> task(generation, &_update_refs_iterator, &work_list);
 909     workers()->run_task(&task);
 910   } else {
 911     ShenandoahGenerationalUpdateHeapRefsTask<false> task(generation, &_update_refs_iterator, &work_list);
 912     workers()->run_task(&task);
 913   }
 914 
 915   if (ShenandoahEnableCardStats) {
 916     // Only do this if we are collecting card stats
 917     ShenandoahScanRemembered* card_scan = old_generation()->card_scan();
 918     assert(card_scan != nullptr, "Card table must exist when card stats are enabled");
 919     card_scan->log_card_stats(nworkers, CARD_STAT_UPDATE_REFS);
 920   }
 921 }
 922 
 923 struct ShenandoahCompositeRegionClosure {
 924   template<typename C1, typename C2>
 925   class Closure : public ShenandoahHeapRegionClosure {
 926   private:
 927     C1 &_c1;
 928     C2 &_c2;
 929 
 930   public:
 931     Closure(C1 &c1, C2 &c2) : ShenandoahHeapRegionClosure(), _c1(c1), _c2(c2) {}
 932 
 933     void heap_region_do(ShenandoahHeapRegion* r) override {
 934       _c1.heap_region_do(r);
 935       _c2.heap_region_do(r);
 936     }
 937 
 938     bool is_thread_safe() override {
 939       return _c1.is_thread_safe() && _c2.is_thread_safe();
 940     }
 941   };
 942 
 943   template<typename C1, typename C2>
 944   static Closure<C1, C2> of(C1 &c1, C2 &c2) {
 945     return Closure<C1, C2>(c1, c2);
 946   }
 947 };
 948 
 949 class ShenandoahUpdateRegionAges : public ShenandoahHeapRegionClosure {
 950 private:
 951   ShenandoahMarkingContext* _ctx;
 952 
 953 public:
 954   explicit ShenandoahUpdateRegionAges(ShenandoahMarkingContext* ctx) : _ctx(ctx) { }
 955 
 956   void heap_region_do(ShenandoahHeapRegion* r) override {
 957     // Maintenance of region age must follow evacuation in order to account for
 958     // evacuation allocations within survivor regions.  We consult region age during
 959     // the subsequent evacuation to determine whether certain objects need to
 960     // be promoted.
 961     if (r->is_young() && r->is_active()) {
 962       HeapWord *tams = _ctx->top_at_mark_start(r);
 963       HeapWord *top = r->top();
 964 
 965       // Allocations move the watermark when top moves.  However, compacting
 966       // objects will sometimes lower top beneath the watermark, after which,
 967       // attempts to read the watermark will assert out (watermark should not be
 968       // higher than top).
 969       if (top > tams) {
 970         // There have been allocations in this region since the start of the cycle.
 971         // Any objects new to this region must not assimilate elevated age.
 972         r->reset_age();
 973       } else {
 974         r->increment_age();
 975       }
 976     }
 977   }
 978 
 979   bool is_thread_safe() override {
 980     return true;
 981   }
 982 };
 983 
 984 void ShenandoahGenerationalHeap::final_update_refs_update_region_states() {
 985   ShenandoahSynchronizePinnedRegionStates pins;
 986   ShenandoahUpdateRegionAges ages(marking_context());
 987   auto cl = ShenandoahCompositeRegionClosure::of(pins, ages);
 988   parallel_heap_region_iterate(&cl);
 989 }
 990 
 991 void ShenandoahGenerationalHeap::complete_degenerated_cycle() {
 992   shenandoah_assert_heaplocked_or_safepoint();
 993   if (!old_generation()->is_parsable()) {
 994     ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_coalesce_and_fill);
 995     coalesce_and_fill_old_regions(false);
 996   }
 997 
 998   old_generation()->maybe_log_promotion_failure_stats(false);
 999 }
1000 
1001 void ShenandoahGenerationalHeap::complete_concurrent_cycle() {
1002   if (!old_generation()->is_parsable()) {
1003     // Class unloading may render the card offsets unusable, so we must rebuild them before
1004     // the next remembered set scan. We _could_ let the control thread do this sometime after
1005     // the global cycle has completed and before the next young collection, but under memory
1006     // pressure the control thread may not have the time (that is, because it's running back
1007     // to back GCs). In that scenario, we would have to make the old regions parsable before
1008     // we could start a young collection. This could delay the start of the young cycle and
1009     // throw off the heuristics.
1010     entry_global_coalesce_and_fill();
1011   }
1012 
1013   old_generation()->maybe_log_promotion_failure_stats(true);
1014 }
1015 
1016 void ShenandoahGenerationalHeap::entry_global_coalesce_and_fill() {
1017   const char* msg = "Coalescing and filling old regions";
1018   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_coalesce_and_fill);
1019 
1020   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
1021   EventMark em("%s", msg);
1022   ShenandoahWorkerScope scope(workers(),
1023                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
1024                               "concurrent coalesce and fill");
1025 
1026   coalesce_and_fill_old_regions(true);
1027 }
1028 
1029 void ShenandoahGenerationalHeap::update_region_ages(ShenandoahMarkingContext* ctx) {
1030   ShenandoahUpdateRegionAges cl(ctx);
1031   parallel_heap_region_iterate(&cl);
1032 }