1 /*
   2  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  27 #include "gc/shenandoah/shenandoahCollectionSetPreselector.hpp"
  28 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  29 #include "gc/shenandoah/shenandoahGeneration.hpp"
  30 #include "gc/shenandoah/shenandoahHeap.hpp"
  31 #include "gc/shenandoah/shenandoahMarkClosures.hpp"
  32 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  33 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
  34 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  35 #include "gc/shenandoah/shenandoahTaskqueue.inline.hpp"
  36 #include "gc/shenandoah/shenandoahUtils.hpp"
  37 #include "gc/shenandoah/shenandoahVerifier.hpp"
  38 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  39 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  40 
  41 #include "utilities/quickSort.hpp"
  42 
  43 class ShenandoahResetUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
  44  private:
  45   ShenandoahHeap* _heap;
  46   ShenandoahMarkingContext* const _ctx;
  47  public:
  48   ShenandoahResetUpdateRegionStateClosure() :
  49     _heap(ShenandoahHeap::heap()),
  50     _ctx(_heap->marking_context()) {}
  51 
  52   void heap_region_do(ShenandoahHeapRegion* r) override {
  53     if (_heap->is_bitmap_slice_committed(r)) {
  54       _ctx->clear_bitmap(r);
  55     }
  56 
  57     if (r->is_active()) {
  58       // Reset live data and set TAMS optimistically. We would recheck these under the pause
  59       // anyway to capture any updates that happened since now.
  60       _ctx->capture_top_at_mark_start(r);
  61       r->clear_live_data();
  62     }
  63   }
  64 
  65   bool is_thread_safe() override { return true; }
  66 };
  67 
  68 class ShenandoahResetBitmapTask : public ShenandoahHeapRegionClosure {
  69  private:
  70   ShenandoahHeap* _heap;
  71   ShenandoahMarkingContext* const _ctx;
  72  public:
  73   ShenandoahResetBitmapTask() :
  74     _heap(ShenandoahHeap::heap()),
  75     _ctx(_heap->marking_context()) {}
  76 
  77   void heap_region_do(ShenandoahHeapRegion* region) {
  78     if (_heap->is_bitmap_slice_committed(region)) {
  79       _ctx->clear_bitmap(region);
  80     }
  81   }
  82 
  83   bool is_thread_safe() { return true; }
  84 };
  85 
  86 // Copy the write-version of the card-table into the read-version, clearing the
  87 // write-copy.
  88 class ShenandoahMergeWriteTable: public ShenandoahHeapRegionClosure {
  89  private:
  90   ShenandoahHeap* _heap;
  91   RememberedScanner* _scanner;
  92  public:
  93   ShenandoahMergeWriteTable() : _heap(ShenandoahHeap::heap()), _scanner(_heap->card_scan()) {}
  94 
  95   virtual void heap_region_do(ShenandoahHeapRegion* r) override {
  96     assert(r->is_old(), "Don't waste time doing this for non-old regions");
  97     _scanner->merge_write_table(r->bottom(), ShenandoahHeapRegion::region_size_words());
  98   }
  99 
 100   virtual bool is_thread_safe() override {
 101     return true;
 102   }
 103 };
 104 
 105 class ShenandoahSquirrelAwayCardTable: public ShenandoahHeapRegionClosure {
 106  private:
 107   ShenandoahHeap* _heap;
 108   RememberedScanner* _scanner;
 109  public:
 110   ShenandoahSquirrelAwayCardTable() :
 111     _heap(ShenandoahHeap::heap()),
 112     _scanner(_heap->card_scan()) {}
 113 
 114   void heap_region_do(ShenandoahHeapRegion* region) {
 115     assert(region->is_old(), "Don't waste time doing this for non-old regions");
 116     _scanner->reset_remset(region->bottom(), ShenandoahHeapRegion::region_size_words());
 117   }
 118 
 119   bool is_thread_safe() { return true; }
 120 };
 121 
 122 void ShenandoahGeneration::confirm_heuristics_mode() {
 123   if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 124     vm_exit_during_initialization(
 125             err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 126                     _heuristics->name()));
 127   }
 128   if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {
 129     vm_exit_during_initialization(
 130             err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 131                     _heuristics->name()));
 132   }
 133 }
 134 
 135 ShenandoahHeuristics* ShenandoahGeneration::initialize_heuristics(ShenandoahMode* gc_mode) {
 136   _heuristics = gc_mode->initialize_heuristics(this);
 137   _heuristics->set_guaranteed_gc_interval(ShenandoahGuaranteedGCInterval);
 138   confirm_heuristics_mode();
 139   return _heuristics;
 140 }
 141 
 142 size_t ShenandoahGeneration::bytes_allocated_since_gc_start() const {
 143   return Atomic::load(&_bytes_allocated_since_gc_start);
 144 }
 145 
 146 void ShenandoahGeneration::reset_bytes_allocated_since_gc_start() {
 147   Atomic::store(&_bytes_allocated_since_gc_start, (size_t)0);
 148 }
 149 
 150 void ShenandoahGeneration::increase_allocated(size_t bytes) {
 151   Atomic::add(&_bytes_allocated_since_gc_start, bytes, memory_order_relaxed);
 152 }
 153 
 154 void ShenandoahGeneration::log_status(const char *msg) const {
 155   typedef LogTarget(Info, gc, ergo) LogGcInfo;
 156 
 157   if (!LogGcInfo::is_enabled()) {
 158     return;
 159   }
 160 
 161   // Not under a lock here, so read each of these once to make sure
 162   // byte size in proper unit and proper unit for byte size are consistent.
 163   size_t v_used = used();
 164   size_t v_used_regions = used_regions_size();
 165   size_t v_soft_max_capacity = soft_max_capacity();
 166   size_t v_max_capacity = max_capacity();
 167   size_t v_available = available();
 168   size_t v_humongous_waste = get_humongous_waste();
 169   LogGcInfo::print("%s: %s generation used: " SIZE_FORMAT "%s, used regions: " SIZE_FORMAT "%s, "
 170                    "humongous waste: " SIZE_FORMAT "%s, soft capacity: " SIZE_FORMAT "%s, max capacity: " SIZE_FORMAT "%s, "
 171                    "available: " SIZE_FORMAT "%s", msg, name(),
 172                    byte_size_in_proper_unit(v_used),              proper_unit_for_byte_size(v_used),
 173                    byte_size_in_proper_unit(v_used_regions),      proper_unit_for_byte_size(v_used_regions),
 174                    byte_size_in_proper_unit(v_humongous_waste),   proper_unit_for_byte_size(v_humongous_waste),
 175                    byte_size_in_proper_unit(v_soft_max_capacity), proper_unit_for_byte_size(v_soft_max_capacity),
 176                    byte_size_in_proper_unit(v_max_capacity),      proper_unit_for_byte_size(v_max_capacity),
 177                    byte_size_in_proper_unit(v_available),         proper_unit_for_byte_size(v_available));
 178 }
 179 
 180 void ShenandoahGeneration::reset_mark_bitmap() {
 181   ShenandoahHeap* heap = ShenandoahHeap::heap();
 182   heap->assert_gc_workers(heap->workers()->active_workers());
 183 
 184   set_mark_incomplete();
 185 
 186   ShenandoahResetBitmapTask task;
 187   parallel_heap_region_iterate(&task);
 188 }
 189 
 190 // The ideal is to swap the remembered set so the safepoint effort is no more than a few pointer manipulations.
 191 // However, limitations in the implementation of the mutator write-barrier make it difficult to simply change the
 192 // location of the card table.  So the interim implementation of swap_remembered_set will copy the write-table
 193 // onto the read-table and will then clear the write-table.
 194 void ShenandoahGeneration::swap_remembered_set() {
 195   // Must be sure that marking is complete before we swap remembered set.
 196   ShenandoahHeap* heap = ShenandoahHeap::heap();
 197   heap->assert_gc_workers(heap->workers()->active_workers());
 198   shenandoah_assert_safepoint();
 199 
 200   // TODO: Eventually, we want replace this with a constant-time exchange of pointers.
 201   ShenandoahSquirrelAwayCardTable task;
 202   heap->old_generation()->parallel_heap_region_iterate(&task);
 203 }
 204 
 205 // Copy the write-version of the card-table into the read-version, clearing the
 206 // write-version. The work is done at a safepoint and in parallel by the GC
 207 // worker threads.
 208 void ShenandoahGeneration::merge_write_table() {
 209   // This should only happen for degenerated cycles
 210   ShenandoahHeap* heap = ShenandoahHeap::heap();
 211   heap->assert_gc_workers(heap->workers()->active_workers());
 212   shenandoah_assert_safepoint();
 213 
 214   ShenandoahMergeWriteTable task;
 215   heap->old_generation()->parallel_heap_region_iterate(&task);
 216 }
 217 
 218 void ShenandoahGeneration::prepare_gc() {
 219   // Invalidate the marking context
 220   set_mark_incomplete();
 221 
 222   // Capture Top At Mark Start for this generation (typically young) and reset mark bitmap.
 223   ShenandoahResetUpdateRegionStateClosure cl;
 224   parallel_heap_region_iterate(&cl);
 225 }
 226 
 227 void ShenandoahGeneration::compute_evacuation_budgets(ShenandoahHeap* const heap) {
 228 
 229   size_t region_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 230   size_t regions_available_to_loan = 0;
 231   size_t minimum_evacuation_reserve = ShenandoahOldCompactionReserve * region_size_bytes;
 232   size_t old_regions_loaned_for_young_evac = 0;
 233 
 234   ShenandoahGeneration* const old_generation = heap->old_generation();
 235   ShenandoahYoungGeneration* const young_generation = heap->young_generation();
 236 
 237   // During initialization and phase changes, it is more likely that fewer objects die young and old-gen
 238   // memory is not yet full (or is in the process of being replaced).  During these times especially, it
 239   // is beneficial to loan memory from old-gen to young-gen during the evacuation and update-refs phases
 240   // of execution.
 241 
 242   // Calculate EvacuationReserve before PromotionReserve.  Evacuation is more critical than promotion.
 243   // If we cannot evacuate old-gen, we will not be able to reclaim old-gen memory.  Promotions are less
 244   // critical.  If we cannot promote, there may be degradation of young-gen memory because old objects
 245   // accumulate there until they can be promoted.  This increases the young-gen marking and evacuation work.
 246 
 247   // Do not fill up old-gen memory with promotions.  Reserve some amount of memory for compaction purposes.
 248   size_t young_evac_reserve_max = 0;
 249 
 250   // First priority is to reclaim the easy garbage out of young-gen.
 251 
 252   // maximum_young_evacuation_reserve is upper bound on memory to be evacuated out of young
 253   const size_t maximum_young_evacuation_reserve = (young_generation->max_capacity() * ShenandoahEvacReserve) / 100;
 254   const size_t young_evacuation_reserve = MIN2(maximum_young_evacuation_reserve, young_generation->available_with_reserve());
 255 
 256   // maximum_old_evacuation_reserve is an upper bound on memory evacuated from old and evacuated to old (promoted),
 257   // clamped by the old generation space available.
 258   //
 259   // Here's the algebra.
 260   // Let SOEP = ShenandoahOldEvacRatioPercent,
 261   //     OE = old evac,
 262   //     YE = young evac, and
 263   //     TE = total evac = OE + YE
 264   // By definition:
 265   //            SOEP/100 = OE/TE
 266   //                     = OE/(OE+YE)
 267   //  => SOEP/(100-SOEP) = OE/((OE+YE)-OE)         // componendo-dividendo: If a/b = c/d, then a/(b-a) = c/(d-c)
 268   //                     = OE/YE
 269   //  =>              OE = YE*SOEP/(100-SOEP)
 270 
 271   // We have to be careful in the event that SOEP is set to 100 by the user.
 272   assert(ShenandoahOldEvacRatioPercent <= 100, "Error");
 273   const size_t old_available = old_generation->available();
 274   const size_t maximum_old_evacuation_reserve = (ShenandoahOldEvacRatioPercent == 100) ?
 275     old_available : MIN2((maximum_young_evacuation_reserve * ShenandoahOldEvacRatioPercent) / (100 - ShenandoahOldEvacRatioPercent),
 276                           old_available);
 277 
 278 
 279   // Second priority is to reclaim garbage out of old-gen if there are old-gen collection candidates.  Third priority
 280   // is to promote as much as we have room to promote.  However, if old-gen memory is in short supply, this means young
 281   // GC is operating under "duress" and was unable to transfer the memory that we would normally expect.  In this case,
 282   // old-gen will refrain from compacting itself in order to allow a quicker young-gen cycle (by avoiding the update-refs
 283   // through ALL of old-gen).  If there is some memory available in old-gen, we will use this for promotions as promotions
 284   // do not add to the update-refs burden of GC.
 285 
 286   ShenandoahOldHeuristics* const old_heuristics = heap->old_heuristics();
 287   size_t old_evacuation_reserve, old_promo_reserve;
 288   if (is_global()) {
 289     // Global GC is typically triggered by user invocation of System.gc(), and typically indicates that there is lots
 290     // of garbage to be reclaimed because we are starting a new phase of execution.  Marking for global GC may take
 291     // significantly longer than typical young marking because we must mark through all old objects.  To expedite
 292     // evacuation and update-refs, we give emphasis to reclaiming garbage first, wherever that garbage is found.
 293     // Global GC will adjust generation sizes to accommodate the collection set it chooses.
 294 
 295     // Set old_promo_reserve to enforce that no regions are preselected for promotion.  Such regions typically
 296     // have relatively high memory utilization.  We still call select_aged_regions() because this will prepare for
 297     // promotions in place, if relevant.
 298     old_promo_reserve = 0;
 299 
 300     // Dedicate all available old memory to old_evacuation reserve.  This may be small, because old-gen is only
 301     // expanded based on an existing mixed evacuation workload at the end of the previous GC cycle.  We'll expand
 302     // the budget for evacuation of old during GLOBAL cset selection.
 303     old_evacuation_reserve = maximum_old_evacuation_reserve;
 304   } else if (old_heuristics->unprocessed_old_collection_candidates() > 0) {
 305     // We reserved all old-gen memory at end of previous GC to hold anticipated evacuations to old-gen.  If this is
 306     // mixed evacuation, reserve all of this memory for compaction of old-gen and do not promote.  Prioritize compaction
 307     // over promotion in order to defragment OLD so that it will be better prepared to efficiently receive promoted memory.
 308     old_evacuation_reserve = maximum_old_evacuation_reserve;
 309     old_promo_reserve = 0;
 310   } else {
 311     // Make all old-evacuation memory for promotion, but if we can't use it all for promotion, we'll allow some evacuation.
 312     old_evacuation_reserve = 0;
 313     old_promo_reserve = maximum_old_evacuation_reserve;
 314   }
 315   assert(old_evacuation_reserve <= old_available, "Error");
 316 
 317   // We see too many old-evacuation failures if we force ourselves to evacuate into regions that are not initially empty.
 318   // So we limit the old-evacuation reserve to unfragmented memory.  Even so, old-evacuation is free to fill in nooks and
 319   // crannies within existing partially used regions and it generally tries to do so.
 320   const size_t old_free_unfragmented = old_generation->free_unaffiliated_regions() * region_size_bytes;
 321   if (old_evacuation_reserve > old_free_unfragmented) {
 322     const size_t delta = old_evacuation_reserve - old_free_unfragmented;
 323     old_evacuation_reserve -= delta;
 324     // Let promo consume fragments of old-gen memory if not global
 325     if (!is_global()) {
 326       old_promo_reserve += delta;
 327     }
 328   }
 329 
 330   // Preselect regions for promotion by evacuation (obtaining the live data to seed promoted_reserve),
 331   // and identify regions that will promote in place. These use the tenuring threshold.
 332   size_t consumed_by_advance_promotion = select_aged_regions(old_promo_reserve);
 333   assert(consumed_by_advance_promotion <= maximum_old_evacuation_reserve, "Cannot promote more than available old-gen memory");
 334 
 335   // Note that unused old_promo_reserve might not be entirely consumed_by_advance_promotion.  Do not transfer this
 336   // to old_evacuation_reserve because this memory is likely very fragmented, and we do not want to increase the likelihood
 337   // of old evacuation failure.
 338 
 339   heap->set_young_evac_reserve(young_evacuation_reserve);
 340   heap->set_old_evac_reserve(old_evacuation_reserve);
 341   heap->set_promoted_reserve(consumed_by_advance_promotion);
 342 
 343   // There is no need to expand OLD because all memory used here was set aside at end of previous GC, except in the
 344   // case of a GLOBAL gc.  During choose_collection_set() of GLOBAL, old will be expanded on demand.
 345 }
 346 
 347 // Having chosen the collection set, adjust the budgets for generational mode based on its composition.  Note
 348 // that young_generation->available() now knows about recently discovered immediate garbage.
 349 //
 350 void ShenandoahGeneration::adjust_evacuation_budgets(ShenandoahHeap* const heap, ShenandoahCollectionSet* const collection_set) {
 351   // We may find that old_evacuation_reserve and/or loaned_for_young_evacuation are not fully consumed, in which case we may
 352   //  be able to increase regions_available_to_loan
 353 
 354   // The role of adjust_evacuation_budgets() is to compute the correct value of regions_available_to_loan and to make
 355   // effective use of this memory, including the remnant memory within these regions that may result from rounding loan to
 356   // integral number of regions.  Excess memory that is available to be loaned is applied to an allocation supplement,
 357   // which allows mutators to allocate memory beyond the current capacity of young-gen on the promise that the loan
 358   // will be repaid as soon as we finish updating references for the recently evacuated collection set.
 359 
 360   // We cannot recalculate regions_available_to_loan by simply dividing old_generation->available() by region_size_bytes
 361   // because the available memory may be distributed between many partially occupied regions that are already holding old-gen
 362   // objects.  Memory in partially occupied regions is not "available" to be loaned.  Note that an increase in old-gen
 363   // available that results from a decrease in memory consumed by old evacuation is not necessarily available to be loaned
 364   // to young-gen.
 365 
 366   size_t region_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 367   const ShenandoahOldGeneration* const old_generation = heap->old_generation();
 368   const ShenandoahYoungGeneration* const young_generation = heap->young_generation();
 369 
 370   size_t old_evacuated = collection_set->get_old_bytes_reserved_for_evacuation();
 371   size_t old_evacuated_committed = (size_t) (ShenandoahOldEvacWaste * old_evacuated);
 372   size_t old_evacuation_reserve = heap->get_old_evac_reserve();
 373 
 374   if (old_evacuated_committed > old_evacuation_reserve) {
 375     // This should only happen due to round-off errors when enforcing ShenandoahOldEvacWaste
 376     assert(old_evacuated_committed <= (33 * old_evacuation_reserve) / 32,
 377            "Round-off errors should be less than 3.125%%, committed: " SIZE_FORMAT ", reserved: " SIZE_FORMAT,
 378            old_evacuated_committed, old_evacuation_reserve);
 379     old_evacuated_committed = old_evacuation_reserve;
 380     // Leave old_evac_reserve as previously configured
 381   } else if (old_evacuated_committed < old_evacuation_reserve) {
 382     // This happens if the old-gen collection consumes less than full budget.
 383     old_evacuation_reserve = old_evacuated_committed;
 384     heap->set_old_evac_reserve(old_evacuation_reserve);
 385   }
 386 
 387   size_t young_advance_promoted = collection_set->get_young_bytes_to_be_promoted();
 388   size_t young_advance_promoted_reserve_used = (size_t) (ShenandoahPromoEvacWaste * young_advance_promoted);
 389 
 390   size_t young_evacuated = collection_set->get_young_bytes_reserved_for_evacuation();
 391   size_t young_evacuated_reserve_used = (size_t) (ShenandoahEvacWaste * young_evacuated);
 392 
 393   size_t total_young_available = young_generation->available_with_reserve();
 394   assert(young_evacuated_reserve_used <= total_young_available, "Cannot evacuate more than is available in young");
 395   heap->set_young_evac_reserve(young_evacuated_reserve_used);
 396 
 397   size_t old_available = old_generation->available();
 398   // Now that we've established the collection set, we know how much memory is really required by old-gen for evacuation
 399   // and promotion reserves.  Try shrinking OLD now in case that gives us a bit more runway for mutator allocations during
 400   // evac and update phases.
 401   size_t old_consumed = old_evacuated_committed + young_advance_promoted_reserve_used;
 402 
 403   if (old_available < old_consumed) {
 404     // This can happen due to round-off errors when adding the results of truncated integer arithmetic.
 405     // We've already truncated old_evacuated_committed.  Truncate young_advance_promoted_reserve_used here.
 406     assert(young_advance_promoted_reserve_used <= (33 * (old_available - old_evacuated_committed)) / 32,
 407            "Round-off errors should be less than 3.125%%, committed: " SIZE_FORMAT ", reserved: " SIZE_FORMAT,
 408            young_advance_promoted_reserve_used, old_available - old_evacuated_committed);
 409     young_advance_promoted_reserve_used = old_available - old_evacuated_committed;
 410     old_consumed = old_evacuated_committed + young_advance_promoted_reserve_used;
 411   }
 412 
 413   assert(old_available >= old_consumed, "Cannot consume (" SIZE_FORMAT ") more than is available (" SIZE_FORMAT ")",
 414          old_consumed, old_available);
 415   size_t excess_old = old_available - old_consumed;
 416   size_t unaffiliated_old_regions = old_generation->free_unaffiliated_regions();
 417   size_t unaffiliated_old = unaffiliated_old_regions * region_size_bytes;
 418   assert(old_available >= unaffiliated_old, "Unaffiliated old is a subset of old available");
 419 
 420   // Make sure old_evac_committed is unaffiliated
 421   if (old_evacuated_committed > 0) {
 422     if (unaffiliated_old > old_evacuated_committed) {
 423       size_t giveaway = unaffiliated_old - old_evacuated_committed;
 424       size_t giveaway_regions = giveaway / region_size_bytes;  // round down
 425       if (giveaway_regions > 0) {
 426         excess_old = MIN2(excess_old, giveaway_regions * region_size_bytes);
 427       } else {
 428         excess_old = 0;
 429       }
 430     } else {
 431       excess_old = 0;
 432     }
 433   }
 434 
 435   // If we find that OLD has excess regions, give them back to YOUNG now to reduce likelihood we run out of allocation
 436   // runway during evacuation and update-refs.
 437   size_t regions_to_xfer = 0;
 438   if (excess_old > unaffiliated_old) {
 439     // we can give back unaffiliated_old (all of unaffiliated is excess)
 440     if (unaffiliated_old_regions > 0) {
 441       regions_to_xfer = unaffiliated_old_regions;
 442     }
 443   } else if (unaffiliated_old_regions > 0) {
 444     // excess_old < unaffiliated old: we can give back MIN(excess_old/region_size_bytes, unaffiliated_old_regions)
 445     size_t excess_regions = excess_old / region_size_bytes;
 446     size_t regions_to_xfer = MIN2(excess_regions, unaffiliated_old_regions);
 447   }
 448 
 449   if (regions_to_xfer > 0) {
 450     bool result = heap->generation_sizer()->transfer_to_young(regions_to_xfer);
 451     assert(excess_old > regions_to_xfer * region_size_bytes, "Cannot xfer more than excess old");
 452     excess_old -= regions_to_xfer * region_size_bytes;
 453     log_info(gc, ergo)("%s transferred " SIZE_FORMAT " excess regions to young before start of evacuation",
 454                        result? "Successfully": "Unsuccessfully", regions_to_xfer);
 455   }
 456 
 457   // Add in the excess_old memory to hold unanticipated promotions, if any.  If there are more unanticipated
 458   // promotions than fit in reserved memory, they will be deferred until a future GC pass.
 459   size_t total_promotion_reserve = young_advance_promoted_reserve_used + excess_old;
 460   heap->set_promoted_reserve(total_promotion_reserve);
 461   heap->reset_promoted_expended();
 462 }
 463 
 464 typedef struct {
 465   ShenandoahHeapRegion* _region;
 466   size_t _live_data;
 467 } AgedRegionData;
 468 
 469 static int compare_by_aged_live(AgedRegionData a, AgedRegionData b) {
 470   if (a._live_data < b._live_data)
 471     return -1;
 472   else if (a._live_data > b._live_data)
 473     return 1;
 474   else return 0;
 475 }
 476 
 477 inline void assert_no_in_place_promotions() {
 478 #ifdef ASSERT
 479   class ShenandoahNoInPlacePromotions : public ShenandoahHeapRegionClosure {
 480   public:
 481     void heap_region_do(ShenandoahHeapRegion *r) override {
 482       assert(r->get_top_before_promote() == nullptr,
 483              "Region " SIZE_FORMAT " should not be ready for in-place promotion", r->index());
 484     }
 485   } cl;
 486   ShenandoahHeap::heap()->heap_region_iterate(&cl);
 487 #endif
 488 }
 489 
 490 // Preselect for inclusion into the collection set regions whose age is at or above tenure age which contain more than
 491 // ShenandoahOldGarbageThreshold amounts of garbage.  We identify these regions by setting the appropriate entry of
 492 // the collection set's preselected regions array to true.  All entries are initialized to false before calling this
 493 // function.
 494 //
 495 // During the subsequent selection of the collection set, we give priority to these promotion set candidates.
 496 // Without this prioritization, we found that the aged regions tend to be ignored because they typically have
 497 // much less garbage and much more live data than the recently allocated "eden" regions.  When aged regions are
 498 // repeatedly excluded from the collection set, the amount of live memory within the young generation tends to
 499 // accumulate and this has the undesirable side effect of causing young-generation collections to require much more
 500 // CPU and wall-clock time.
 501 //
 502 // A second benefit of treating aged regions differently than other regions during collection set selection is
 503 // that this allows us to more accurately budget memory to hold the results of evacuation.  Memory for evacuation
 504 // of aged regions must be reserved in the old generation.  Memory for evacuation of all other regions must be
 505 // reserved in the young generation.
 506 size_t ShenandoahGeneration::select_aged_regions(size_t old_available) {
 507 
 508   // There should be no regions configured for subsequent in-place-promotions carried over from the previous cycle.
 509   assert_no_in_place_promotions();
 510 
 511   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 512   assert(heap->mode()->is_generational(), "Only in generational mode");
 513   bool* const candidate_regions_for_promotion_by_copy = heap->collection_set()->preselected_regions();
 514   ShenandoahMarkingContext* const ctx = heap->marking_context();
 515 
 516   const uint tenuring_threshold = heap->age_census()->tenuring_threshold();
 517   const size_t old_garbage_threshold = (ShenandoahHeapRegion::region_size_bytes() * ShenandoahOldGarbageThreshold) / 100;
 518 
 519   size_t old_consumed = 0;
 520   size_t promo_potential = 0;
 521   size_t candidates = 0;
 522 
 523   // Tracks the padding of space above top in regions eligible for promotion in place
 524   size_t promote_in_place_pad = 0;
 525 
 526   // Sort the promotion-eligible regions in order of increasing live-data-bytes so that we can first reclaim regions that require
 527   // less evacuation effort.  This prioritizes garbage first, expanding the allocation pool early before we reclaim regions that
 528   // have more live data.
 529   const size_t num_regions = heap->num_regions();
 530 
 531   ResourceMark rm;
 532   AgedRegionData* sorted_regions = NEW_RESOURCE_ARRAY(AgedRegionData, num_regions);
 533 
 534   for (size_t i = 0; i < num_regions; i++) {
 535     ShenandoahHeapRegion* const r = heap->get_region(i);
 536     if (r->is_empty() || !r->has_live() || !r->is_young() || !r->is_regular()) {
 537       // skip over regions that aren't regular young with some live data
 538       continue;
 539     }
 540     if (r->age() >= tenuring_threshold) {
 541       if ((r->garbage() < old_garbage_threshold)) {
 542         // This tenure-worthy region has too little garbage, so we do not want to expend the copying effort to
 543         // reclaim the garbage; instead this region may be eligible for promotion-in-place to the
 544         // old generation.
 545         HeapWord* tams = ctx->top_at_mark_start(r);
 546         HeapWord* original_top = r->top();
 547         if (!heap->is_concurrent_old_mark_in_progress() && tams == original_top) {
 548           // No allocations from this region have been made during concurrent mark. It meets all the criteria
 549           // for in-place-promotion. Though we only need the value of top when we fill the end of the region,
 550           // we use this field to indicate that this region should be promoted in place during the evacuation
 551           // phase.
 552           r->save_top_before_promote();
 553 
 554           size_t remnant_size = r->free() / HeapWordSize;
 555           if (remnant_size > ShenandoahHeap::min_fill_size()) {
 556             ShenandoahHeap::fill_with_object(original_top, remnant_size);
 557             // Fill the remnant memory within this region to assure no allocations prior to promote in place.  Otherwise,
 558             // newly allocated objects will not be parsable when promote in place tries to register them.  Furthermore, any
 559             // new allocations would not necessarily be eligible for promotion.  This addresses both issues.
 560             r->set_top(r->end());
 561             promote_in_place_pad += remnant_size * HeapWordSize;
 562           } else {
 563             // Since the remnant is so small that it cannot be filled, we don't have to worry about any accidental
 564             // allocations occurring within this region before the region is promoted in place.
 565           }
 566         }
 567         // Else, we do not promote this region (either in place or by copy) because it has received new allocations.
 568 
 569         // During evacuation, we exclude from promotion regions for which age > tenure threshold, garbage < garbage-threshold,
 570         //  and get_top_before_promote() != tams
 571       } else {
 572         // Record this promotion-eligible candidate region. After sorting and selecting the best candidates below,
 573         // we may still decide to exclude this promotion-eligible region from the current collection set.  If this
 574         // happens, we will consider this region as part of the anticipated promotion potential for the next GC
 575         // pass; see further below.
 576         sorted_regions[candidates]._region = r;
 577         sorted_regions[candidates++]._live_data = r->get_live_data_bytes();
 578       }
 579     } else {
 580       // We only evacuate & promote objects from regular regions whose garbage() is above old-garbage-threshold.
 581       // Objects in tenure-worthy regions with less garbage are promoted in place. These take a different path to
 582       // old-gen.  Regions excluded from promotion because their garbage content is too low (causing us to anticipate that
 583       // the region would be promoted in place) may be eligible for evacuation promotion by the time promotion takes
 584       // place during a subsequent GC pass because more garbage is found within the region between now and then.  This
 585       // should not happen if we are properly adapting the tenure age.  The theory behind adaptive tenuring threshold
 586       // is to choose the youngest age that demonstrates no "significant" further loss of population since the previous
 587       // age.  If not this, we expect the tenure age to demonstrate linear population decay for at least two population
 588       // samples, whereas we expect to observe exponential population decay for ages younger than the tenure age.
 589       //
 590       // In the case that certain regions which were anticipated to be promoted in place need to be promoted by
 591       // evacuation, it may be the case that there is not sufficient reserve within old-gen to hold evacuation of
 592       // these regions.  The likely outcome is that these regions will not be selected for evacuation or promotion
 593       // in the current cycle and we will anticipate that they will be promoted in the next cycle.  This will cause
 594       // us to reserve more old-gen memory so that these objects can be promoted in the subsequent cycle.
 595       //
 596       // TODO:
 597       //   If we are auto-tuning the tenure age and regions that were anticipated to be promoted in place end up
 598       //   being promoted by evacuation, this event should feed into the tenure-age-selection heuristic so that
 599       //   the tenure age can be increased.
 600       if (heap->is_aging_cycle() && (r->age() + 1 == tenuring_threshold)) {
 601         if (r->garbage() >= old_garbage_threshold) {
 602           promo_potential += r->get_live_data_bytes();
 603         }
 604       }
 605     }
 606     // Note that we keep going even if one region is excluded from selection.
 607     // Subsequent regions may be selected if they have smaller live data.
 608   }
 609   // Sort in increasing order according to live data bytes.  Note that candidates represents the number of regions
 610   // that qualify to be promoted by evacuation.
 611   if (candidates > 0) {
 612     size_t selected_regions = 0;
 613     size_t selected_live = 0;
 614     QuickSort::sort<AgedRegionData>(sorted_regions, candidates, compare_by_aged_live, false);
 615     for (size_t i = 0; i < candidates; i++) {
 616       ShenandoahHeapRegion* const region = sorted_regions[i]._region;
 617       size_t region_live_data = sorted_regions[i]._live_data;
 618       size_t promotion_need = (size_t) (region_live_data * ShenandoahPromoEvacWaste);
 619       if (old_consumed + promotion_need <= old_available) {
 620         old_consumed += promotion_need;
 621         candidate_regions_for_promotion_by_copy[region->index()] = true;
 622         selected_regions++;
 623         selected_live += region_live_data;
 624       } else {
 625         // We rejected this promotable region from the collection set because we had no room to hold its copy.
 626         // Add this region to promo potential for next GC.
 627         promo_potential += region_live_data;
 628         assert(!candidate_regions_for_promotion_by_copy[region->index()], "Shouldn't be selected");
 629       }
 630       // We keep going even if one region is excluded from selection because we need to accumulate all eligible
 631       // regions that are not preselected into promo_potential
 632     }
 633     log_info(gc)("Preselected " SIZE_FORMAT " regions containing " SIZE_FORMAT " live bytes,"
 634                  " consuming: " SIZE_FORMAT " of budgeted: " SIZE_FORMAT,
 635                  selected_regions, selected_live, old_consumed, old_available);
 636   }
 637   heap->set_pad_for_promote_in_place(promote_in_place_pad);
 638   heap->set_promotion_potential(promo_potential);
 639   return old_consumed;
 640 }
 641 
 642 void ShenandoahGeneration::prepare_regions_and_collection_set(bool concurrent) {
 643   ShenandoahHeap* heap = ShenandoahHeap::heap();
 644   ShenandoahCollectionSet* collection_set = heap->collection_set();
 645   bool is_generational = heap->mode()->is_generational();
 646 
 647   assert(!heap->is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
 648   assert(!is_old(), "Only YOUNG and GLOBAL GC perform evacuations");
 649   {
 650     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_update_region_states :
 651                             ShenandoahPhaseTimings::degen_gc_final_update_region_states);
 652     ShenandoahFinalMarkUpdateRegionStateClosure cl(complete_marking_context());
 653     parallel_heap_region_iterate(&cl);
 654 
 655     if (is_young()) {
 656       // We always need to update the watermark for old regions. If there
 657       // are mixed collections pending, we also need to synchronize the
 658       // pinned status for old regions. Since we are already visiting every
 659       // old region here, go ahead and sync the pin status too.
 660       ShenandoahFinalMarkUpdateRegionStateClosure old_cl(nullptr);
 661       heap->old_generation()->parallel_heap_region_iterate(&old_cl);
 662     }
 663   }
 664 
 665   // Tally the census counts and compute the adaptive tenuring threshold
 666   if (is_generational && ShenandoahGenerationalAdaptiveTenuring && !ShenandoahGenerationalCensusAtEvac) {
 667     // Objects above TAMS weren't included in the age census. Since they were all
 668     // allocated in this cycle they belong in the age 0 cohort. We walk over all
 669     // young regions and sum the volume of objects between TAMS and top.
 670     ShenandoahUpdateCensusZeroCohortClosure age0_cl(complete_marking_context());
 671     heap->young_generation()->heap_region_iterate(&age0_cl);
 672     size_t age0_pop = age0_cl.get_population();
 673 
 674     // Age table updates
 675     ShenandoahAgeCensus* census = heap->age_census();
 676     census->prepare_for_census_update();
 677     // Update the global census, including the missed age 0 cohort above,
 678     // along with the census during marking, and compute the tenuring threshold
 679     census->update_census(age0_pop);
 680   }
 681 
 682   {
 683     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::choose_cset :
 684                             ShenandoahPhaseTimings::degen_gc_choose_cset);
 685 
 686     collection_set->clear();
 687     ShenandoahHeapLocker locker(heap->lock());
 688     if (is_generational) {
 689       // Seed the collection set with resource area-allocated
 690       // preselected regions, which are removed when we exit this scope.
 691       ResourceMark rm;
 692       ShenandoahCollectionSetPreselector preselector(collection_set, heap->num_regions());
 693 
 694       // TODO: young_available can include available (between top() and end()) within each young region that is not
 695       // part of the collection set.  Making this memory available to the young_evacuation_reserve allows a larger
 696       // young collection set to be chosen when available memory is under extreme pressure.  Implementing this "improvement"
 697       // is tricky, because the incremental construction of the collection set actually changes the amount of memory
 698       // available to hold evacuated young-gen objects.  As currently implemented, the memory that is available within
 699       // non-empty regions that are not selected as part of the collection set can be allocated by the mutator while
 700       // GC is evacuating and updating references.
 701 
 702       // Find the amount that will be promoted, regions that will be promoted in
 703       // place, and preselect older regions that will be promoted by evacuation.
 704       compute_evacuation_budgets(heap);
 705 
 706       // Choose the collection set, including the regions preselected above for
 707       // promotion into the old generation.
 708       _heuristics->choose_collection_set(collection_set);
 709       if (!collection_set->is_empty()) {
 710         // only make use of evacuation budgets when we are evacuating
 711         adjust_evacuation_budgets(heap, collection_set);
 712       }
 713 
 714       if (is_global()) {
 715         // We have just chosen a collection set for a global cycle. The mark bitmap covering old regions is complete, so
 716         // the remembered set scan can use that to avoid walking into garbage. When the next old mark begins, we will
 717         // use the mark bitmap to make the old regions parsable by coalescing and filling any unmarked objects. Thus,
 718         // we prepare for old collections by remembering which regions are old at this time. Note that any objects
 719         // promoted into old regions will be above TAMS, and so will be considered marked. However, free regions that
 720         // become old after this point will not be covered correctly by the mark bitmap, so we must be careful not to
 721         // coalesce those regions. Only the old regions which are not part of the collection set at this point are
 722         // eligible for coalescing. As implemented now, this has the side effect of possibly initiating mixed-evacuations
 723         // after a global cycle for old regions that were not included in this collection set.
 724         assert(heap->old_generation()->is_mark_complete(), "Expected old generation mark to be complete after global cycle.");
 725         heap->old_heuristics()->prepare_for_old_collections();
 726         log_info(gc)("After choosing global collection set, mixed candidates: " UINT32_FORMAT ", coalescing candidates: " SIZE_FORMAT,
 727                      heap->old_heuristics()->unprocessed_old_collection_candidates(),
 728                      heap->old_heuristics()->coalesce_and_fill_candidates_count());
 729       }
 730     } else {
 731       _heuristics->choose_collection_set(collection_set);
 732     }
 733   }
 734 
 735   // Freeset construction uses reserve quantities if they are valid
 736   heap->set_evacuation_reserve_quantities(true);
 737   {
 738     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_rebuild_freeset :
 739                             ShenandoahPhaseTimings::degen_gc_final_rebuild_freeset);
 740     ShenandoahHeapLocker locker(heap->lock());
 741     size_t young_cset_regions, old_cset_regions;
 742 
 743     // We are preparing for evacuation.  At this time, we ignore cset region tallies.
 744     size_t first_old, last_old, num_old;
 745     heap->free_set()->prepare_to_rebuild(young_cset_regions, old_cset_regions, first_old, last_old, num_old);
 746     heap->free_set()->rebuild(young_cset_regions, old_cset_regions);
 747   }
 748   heap->set_evacuation_reserve_quantities(false);
 749 }
 750 
 751 bool ShenandoahGeneration::is_bitmap_clear() {
 752   ShenandoahHeap* heap = ShenandoahHeap::heap();
 753   ShenandoahMarkingContext* context = heap->marking_context();
 754   const size_t num_regions = heap->num_regions();
 755   for (size_t idx = 0; idx < num_regions; idx++) {
 756     ShenandoahHeapRegion* r = heap->get_region(idx);
 757     if (contains(r) && r->is_affiliated()) {
 758       if (heap->is_bitmap_slice_committed(r) && (context->top_at_mark_start(r) > r->bottom()) &&
 759           !context->is_bitmap_clear_range(r->bottom(), r->end())) {
 760         return false;
 761       }
 762     }
 763   }
 764   return true;
 765 }
 766 
 767 bool ShenandoahGeneration::is_mark_complete() {
 768   return _is_marking_complete.is_set();
 769 }
 770 
 771 void ShenandoahGeneration::set_mark_complete() {
 772   _is_marking_complete.set();
 773 }
 774 
 775 void ShenandoahGeneration::set_mark_incomplete() {
 776   _is_marking_complete.unset();
 777 }
 778 
 779 ShenandoahMarkingContext* ShenandoahGeneration::complete_marking_context() {
 780   assert(is_mark_complete(), "Marking must be completed.");
 781   return ShenandoahHeap::heap()->marking_context();
 782 }
 783 
 784 void ShenandoahGeneration::cancel_marking() {
 785   log_info(gc)("Cancel marking: %s", name());
 786   if (is_concurrent_mark_in_progress()) {
 787     set_mark_incomplete();
 788   }
 789   _task_queues->clear();
 790   ref_processor()->abandon_partial_discovery();
 791   set_concurrent_mark_in_progress(false);
 792 }
 793 
 794 ShenandoahGeneration::ShenandoahGeneration(ShenandoahGenerationType type,
 795                                            uint max_workers,
 796                                            size_t max_capacity,
 797                                            size_t soft_max_capacity) :
 798   _type(type),
 799   _task_queues(new ShenandoahObjToScanQueueSet(max_workers)),
 800   _ref_processor(new ShenandoahReferenceProcessor(MAX2(max_workers, 1U))),
 801   _affiliated_region_count(0), _humongous_waste(0), _used(0), _bytes_allocated_since_gc_start(0),
 802   _max_capacity(max_capacity), _soft_max_capacity(soft_max_capacity),
 803   _heuristics(nullptr) {
 804   _is_marking_complete.set();
 805   assert(max_workers > 0, "At least one queue");
 806   for (uint i = 0; i < max_workers; ++i) {
 807     ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue();
 808     _task_queues->register_queue(i, task_queue);
 809   }
 810 }
 811 
 812 ShenandoahGeneration::~ShenandoahGeneration() {
 813   for (uint i = 0; i < _task_queues->size(); ++i) {
 814     ShenandoahObjToScanQueue* q = _task_queues->queue(i);
 815     delete q;
 816   }
 817   delete _task_queues;
 818 }
 819 
 820 void ShenandoahGeneration::reserve_task_queues(uint workers) {
 821   _task_queues->reserve(workers);
 822 }
 823 
 824 ShenandoahObjToScanQueueSet* ShenandoahGeneration::old_gen_task_queues() const {
 825   return nullptr;
 826 }
 827 
 828 void ShenandoahGeneration::scan_remembered_set(bool is_concurrent) {
 829   assert(is_young(), "Should only scan remembered set for young generation.");
 830 
 831   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 832   uint nworkers = heap->workers()->active_workers();
 833   reserve_task_queues(nworkers);
 834 
 835   ShenandoahReferenceProcessor* rp = ref_processor();
 836   ShenandoahRegionChunkIterator work_list(nworkers);
 837   ShenandoahScanRememberedTask task(task_queues(), old_gen_task_queues(), rp, &work_list, is_concurrent);
 838   heap->assert_gc_workers(nworkers);
 839   heap->workers()->run_task(&task);
 840   if (ShenandoahEnableCardStats) {
 841     assert(heap->card_scan() != nullptr, "Not generational");
 842     heap->card_scan()->log_card_stats(nworkers, CARD_STAT_SCAN_RS);
 843   }
 844 }
 845 
 846 size_t ShenandoahGeneration::increment_affiliated_region_count() {
 847   shenandoah_assert_heaplocked_or_fullgc_safepoint();
 848   // During full gc, multiple GC worker threads may change region affiliations without a lock.  No lock is enforced
 849   // on read and write of _affiliated_region_count.  At the end of full gc, a single thread overwrites the count with
 850   // a coherent value.
 851   _affiliated_region_count++;
 852   return _affiliated_region_count;
 853 }
 854 
 855 size_t ShenandoahGeneration::decrement_affiliated_region_count() {
 856   shenandoah_assert_heaplocked_or_fullgc_safepoint();
 857   // During full gc, multiple GC worker threads may change region affiliations without a lock.  No lock is enforced
 858   // on read and write of _affiliated_region_count.  At the end of full gc, a single thread overwrites the count with
 859   // a coherent value.
 860   _affiliated_region_count--;
 861   // TODO: REMOVE IS_GLOBAL() QUALIFIER AFTER WE FIX GLOBAL AFFILIATED REGION ACCOUNTING
 862   assert(is_global() || ShenandoahHeap::heap()->is_full_gc_in_progress() ||
 863          (_used + _humongous_waste <= _affiliated_region_count * ShenandoahHeapRegion::region_size_bytes()),
 864          "used + humongous cannot exceed regions");
 865   return _affiliated_region_count;
 866 }
 867 
 868 size_t ShenandoahGeneration::increase_affiliated_region_count(size_t delta) {
 869   shenandoah_assert_heaplocked_or_fullgc_safepoint();
 870   _affiliated_region_count += delta;
 871   return _affiliated_region_count;
 872 }
 873 
 874 size_t ShenandoahGeneration::decrease_affiliated_region_count(size_t delta) {
 875   shenandoah_assert_heaplocked_or_fullgc_safepoint();
 876   assert(_affiliated_region_count >= delta, "Affiliated region count cannot be negative");
 877 
 878   _affiliated_region_count -= delta;
 879   // TODO: REMOVE IS_GLOBAL() QUALIFIER AFTER WE FIX GLOBAL AFFILIATED REGION ACCOUNTING
 880   assert(is_global() || ShenandoahHeap::heap()->is_full_gc_in_progress() ||
 881          (_used + _humongous_waste <= _affiliated_region_count * ShenandoahHeapRegion::region_size_bytes()),
 882          "used + humongous cannot exceed regions");
 883   return _affiliated_region_count;
 884 }
 885 
 886 void ShenandoahGeneration::establish_usage(size_t num_regions, size_t num_bytes, size_t humongous_waste) {
 887   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 888   _affiliated_region_count = num_regions;
 889   _used = num_bytes;
 890   _humongous_waste = humongous_waste;
 891 }
 892 
 893 void ShenandoahGeneration::increase_used(size_t bytes) {
 894   Atomic::add(&_used, bytes);
 895 }
 896 
 897 void ShenandoahGeneration::increase_humongous_waste(size_t bytes) {
 898   if (bytes > 0) {
 899     Atomic::add(&_humongous_waste, bytes);
 900   }
 901 }
 902 
 903 void ShenandoahGeneration::decrease_humongous_waste(size_t bytes) {
 904   if (bytes > 0) {
 905     assert(ShenandoahHeap::heap()->is_full_gc_in_progress() || (_humongous_waste >= bytes),
 906            "Waste (" SIZE_FORMAT ") cannot be negative (after subtracting " SIZE_FORMAT ")", _humongous_waste, bytes);
 907     Atomic::sub(&_humongous_waste, bytes);
 908   }
 909 }
 910 
 911 void ShenandoahGeneration::decrease_used(size_t bytes) {
 912   // TODO: REMOVE IS_GLOBAL() QUALIFIER AFTER WE FIX GLOBAL AFFILIATED REGION ACCOUNTING
 913   assert(is_global() || ShenandoahHeap::heap()->is_full_gc_in_progress() ||
 914          (_used >= bytes), "cannot reduce bytes used by generation below zero");
 915   Atomic::sub(&_used, bytes);
 916 }
 917 
 918 size_t ShenandoahGeneration::used_regions() const {
 919   return _affiliated_region_count;
 920 }
 921 
 922 size_t ShenandoahGeneration::free_unaffiliated_regions() const {
 923   size_t result = max_capacity() / ShenandoahHeapRegion::region_size_bytes();
 924   if (_affiliated_region_count > result) {
 925     result = 0;
 926   } else {
 927     result -= _affiliated_region_count;
 928   }
 929   return result;
 930 }
 931 
 932 size_t ShenandoahGeneration::used_regions_size() const {
 933   return _affiliated_region_count * ShenandoahHeapRegion::region_size_bytes();
 934 }
 935 
 936 size_t ShenandoahGeneration::available() const {
 937   return available(max_capacity());
 938 }
 939 
 940 // For ShenandoahYoungGeneration, Include the young available that may have been reserved for the Collector.
 941 size_t ShenandoahGeneration::available_with_reserve() const {
 942   return available(max_capacity());
 943 }
 944 
 945 size_t ShenandoahGeneration::soft_available() const {
 946   return available(soft_max_capacity());
 947 }
 948 
 949 size_t ShenandoahGeneration::available(size_t capacity) const {
 950   size_t in_use = used() + get_humongous_waste();
 951   return in_use > capacity ? 0 : capacity - in_use;
 952 }
 953 
 954 void ShenandoahGeneration::increase_capacity(size_t increment) {
 955   shenandoah_assert_heaplocked_or_safepoint();
 956 
 957   // We do not enforce that new capacity >= heap->max_size_for(this).  The maximum generation size is treated as a rule of thumb
 958   // which may be violated during certain transitions, such as when we are forcing transfers for the purpose of promoting regions
 959   // in place.
 960   // TODO: REMOVE IS_GLOBAL() QUALIFIER AFTER WE FIX GLOBAL AFFILIATED REGION ACCOUNTING
 961   assert(is_global() || ShenandoahHeap::heap()->is_full_gc_in_progress() ||
 962          (_max_capacity + increment <= ShenandoahHeap::heap()->max_capacity()), "Generation cannot be larger than heap size");
 963   assert(increment % ShenandoahHeapRegion::region_size_bytes() == 0, "Generation capacity must be multiple of region size");
 964   _max_capacity += increment;
 965 
 966   // This detects arithmetic wraparound on _used
 967   // TODO: REMOVE IS_GLOBAL() QUALIFIER AFTER WE FIX GLOBAL AFFILIATED REGION ACCOUNTING
 968   assert(is_global() || ShenandoahHeap::heap()->is_full_gc_in_progress() ||
 969          (_affiliated_region_count * ShenandoahHeapRegion::region_size_bytes() >= _used),
 970          "Affiliated regions must hold more than what is currently used");
 971 }
 972 
 973 void ShenandoahGeneration::decrease_capacity(size_t decrement) {
 974   shenandoah_assert_heaplocked_or_safepoint();
 975 
 976   // We do not enforce that new capacity >= heap->min_size_for(this).  The minimum generation size is treated as a rule of thumb
 977   // which may be violated during certain transitions, such as when we are forcing transfers for the purpose of promoting regions
 978   // in place.
 979   assert(decrement % ShenandoahHeapRegion::region_size_bytes() == 0, "Generation capacity must be multiple of region size");
 980   assert(_max_capacity >= decrement, "Generation capacity cannot be negative");
 981 
 982   _max_capacity -= decrement;
 983 
 984   // This detects arithmetic wraparound on _used
 985   // TODO: REMOVE IS_GLOBAL() QUALIFIER AFTER WE FIX GLOBAL AFFILIATED REGION ACCOUNTING
 986   assert(is_global() || ShenandoahHeap::heap()->is_full_gc_in_progress() ||
 987          (_affiliated_region_count * ShenandoahHeapRegion::region_size_bytes() >= _used),
 988          "Affiliated regions must hold more than what is currently used");
 989   // TODO: REMOVE IS_GLOBAL() QUALIFIER AFTER WE FIX GLOBAL AFFILIATED REGION ACCOUNTING
 990   assert(is_global() || ShenandoahHeap::heap()->is_full_gc_in_progress() ||
 991          (_used <= _max_capacity), "Cannot use more than capacity");
 992   // TODO: REMOVE IS_GLOBAL() QUALIFIER AFTER WE FIX GLOBAL AFFILIATED REGION ACCOUNTING
 993   assert(is_global() || ShenandoahHeap::heap()->is_full_gc_in_progress() ||
 994          (_affiliated_region_count * ShenandoahHeapRegion::region_size_bytes() <= _max_capacity),
 995          "Cannot use more than capacity");
 996 }
 997 
 998 void ShenandoahGeneration::record_success_concurrent(bool abbreviated) {
 999   heuristics()->record_success_concurrent(abbreviated);
1000   ShenandoahHeap::heap()->shenandoah_policy()->record_success_concurrent(is_young(), abbreviated);
1001 }