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