1 /*
   2  * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2013, 2022, Red Hat, Inc. All rights reserved.
   4  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 
  28 #include "cds/aotMappedHeapWriter.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "gc/shared/classUnloadingContext.hpp"
  31 #include "gc/shared/fullGCForwarding.hpp"
  32 #include "gc/shared/gc_globals.hpp"
  33 #include "gc/shared/gcArguments.hpp"
  34 #include "gc/shared/gcTimer.hpp"
  35 #include "gc/shared/gcTraceTime.inline.hpp"
  36 #include "gc/shared/locationPrinter.inline.hpp"
  37 #include "gc/shared/memAllocator.hpp"
  38 #include "gc/shared/plab.hpp"
  39 #include "gc/shared/tlab_globals.hpp"
  40 #include "gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp"
  41 #include "gc/shenandoah/heuristics/shenandoahYoungHeuristics.hpp"
  42 #include "gc/shenandoah/mode/shenandoahGenerationalMode.hpp"
  43 #include "gc/shenandoah/mode/shenandoahPassiveMode.hpp"
  44 #include "gc/shenandoah/mode/shenandoahSATBMode.hpp"
  45 #include "gc/shenandoah/shenandoahAllocator.hpp"
  46 #include "gc/shenandoah/shenandoahAllocRate.inline.hpp"
  47 #include "gc/shenandoah/shenandoahAllocRequest.hpp"
  48 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  49 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  50 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
  51 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  52 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  53 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
  54 #include "gc/shenandoah/shenandoahControlThread.hpp"
  55 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  56 #include "gc/shenandoah/shenandoahGenerationalEvacuationTask.hpp"
  57 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp"
  58 #include "gc/shenandoah/shenandoahGlobalGeneration.hpp"
  59 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  60 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  61 #include "gc/shenandoah/shenandoahHeapRegionClosures.hpp"
  62 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  63 #include "gc/shenandoah/shenandoahInitLogger.hpp"
  64 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  65 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
  66 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  67 #include "gc/shenandoah/shenandoahObjArrayAllocator.hpp"
  68 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
  69 #include "gc/shenandoah/shenandoahPadding.hpp"
  70 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
  71 #include "gc/shenandoah/shenandoahPartitionAllocator.hpp"
  72 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  73 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  74 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  75 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
  76 #include "gc/shenandoah/shenandoahStackChunkGCData.inline.hpp"
  77 #include "gc/shenandoah/shenandoahStackWatermark.hpp"
  78 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  79 #include "gc/shenandoah/shenandoahUncommitThread.hpp"
  80 #include "gc/shenandoah/shenandoahUtils.hpp"
  81 #include "gc/shenandoah/shenandoahVerifier.hpp"
  82 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  83 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  84 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  85 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  86 #include "memory/allocation.hpp"
  87 #include "memory/classLoaderMetaspace.hpp"
  88 #include "memory/memoryReserver.hpp"
  89 #include "memory/metaspaceUtils.hpp"
  90 #include "memory/universe.hpp"
  91 #include "nmt/mallocTracker.hpp"
  92 #include "nmt/memTracker.hpp"
  93 #include "oops/compressedOops.inline.hpp"
  94 #include "prims/jvmtiTagMap.hpp"
  95 #include "runtime/atomic.hpp"
  96 #include "runtime/atomicAccess.hpp"
  97 #include "runtime/globals.hpp"
  98 #include "runtime/interfaceSupport.inline.hpp"
  99 #include "runtime/java.hpp"
 100 #include "runtime/orderAccess.hpp"
 101 #include "runtime/safepointMechanism.hpp"
 102 #include "runtime/stackWatermarkSet.hpp"
 103 #include "runtime/threads.hpp"
 104 #include "runtime/vmThread.hpp"
 105 #include "utilities/events.hpp"
 106 #include "utilities/globalDefinitions.hpp"
 107 #include "utilities/powerOfTwo.hpp"
 108 #if INCLUDE_JFR
 109 #include "gc/shenandoah/shenandoahJfrSupport.hpp"
 110 #endif
 111 
 112 class ShenandoahPretouchHeapTask : public WorkerTask {
 113 private:
 114   ShenandoahRegionIterator _regions;
 115   const size_t _page_size;
 116 public:
 117   ShenandoahPretouchHeapTask(size_t page_size) :
 118     WorkerTask("Shenandoah Pretouch Heap"),
 119     _page_size(page_size) {}
 120 
 121   virtual void work(uint worker_id) {
 122     ShenandoahHeapRegion* r = _regions.next();
 123     while (r != nullptr) {
 124       if (r->is_committed()) {
 125         os::pretouch_memory(r->bottom(), r->end(), _page_size);
 126       }
 127       r = _regions.next();
 128     }
 129   }
 130 };
 131 
 132 class ShenandoahPretouchBitmapTask : public WorkerTask {
 133 private:
 134   ShenandoahRegionIterator _regions;
 135   char* _bitmap_base;
 136   const size_t _bitmap_size;
 137   const size_t _page_size;
 138 public:
 139   ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :
 140     WorkerTask("Shenandoah Pretouch Bitmap"),
 141     _bitmap_base(bitmap_base),
 142     _bitmap_size(bitmap_size),
 143     _page_size(page_size) {}
 144 
 145   virtual void work(uint worker_id) {
 146     ShenandoahHeapRegion* r = _regions.next();
 147     while (r != nullptr) {
 148       size_t start = r->index()       * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 149       size_t end   = (r->index() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 150       assert (end <= _bitmap_size, "end is sane: %zu < %zu", end, _bitmap_size);
 151 
 152       if (r->is_committed()) {
 153         os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
 154       }
 155 
 156       r = _regions.next();
 157     }
 158   }
 159 };
 160 
 161 static ReservedSpace reserve(size_t size, size_t preferred_page_size) {
 162   // When a page size is given we don't want to mix large
 163   // and normal pages. If the size is not a multiple of the
 164   // page size it will be aligned up to achieve this.
 165   size_t alignment = os::vm_allocation_granularity();
 166   if (preferred_page_size != os::vm_page_size()) {
 167     alignment = MAX2(preferred_page_size, alignment);
 168     size = align_up(size, alignment);
 169   }
 170 
 171   const ReservedSpace reserved = MemoryReserver::reserve(size, alignment, preferred_page_size, mtGC);
 172   if (!reserved.is_reserved()) {
 173     vm_exit_during_initialization("Could not reserve space");
 174   }
 175   return reserved;
 176 }
 177 
 178 jint ShenandoahHeap::initialize() {
 179   //
 180   // Figure out heap sizing
 181   //
 182 
 183   size_t init_byte_size = InitialHeapSize;
 184   size_t min_byte_size  = MinHeapSize;
 185   size_t max_byte_size  = MaxHeapSize;
 186   size_t heap_alignment = HeapAlignment;
 187 
 188   size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 189 
 190   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
 191   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
 192 
 193   _num_regions = ShenandoahHeapRegion::region_count();
 194   assert(_num_regions == (max_byte_size / reg_size_bytes),
 195          "Regions should cover entire heap exactly: %zu != %zu/%zu",
 196          _num_regions, max_byte_size, reg_size_bytes);
 197 
 198   size_t num_committed_regions = init_byte_size / reg_size_bytes;
 199   num_committed_regions = MIN2(num_committed_regions, _num_regions);
 200   assert(num_committed_regions <= _num_regions, "sanity");
 201   _initial_size = num_committed_regions * reg_size_bytes;
 202 
 203   size_t num_min_regions = min_byte_size / reg_size_bytes;
 204   num_min_regions = MIN2(num_min_regions, _num_regions);
 205   assert(num_min_regions <= _num_regions, "sanity");
 206   _minimum_size = num_min_regions * reg_size_bytes;
 207 
 208   _soft_max_size.store_relaxed(clamp(SoftMaxHeapSize, min_capacity(), max_capacity()));
 209 
 210   _committed.store_relaxed(_initial_size);
 211 
 212   size_t heap_page_size   = UseLargePages ? os::large_page_size() : os::vm_page_size();
 213   size_t bitmap_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
 214   size_t region_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
 215 
 216   //
 217   // Reserve and commit memory for heap
 218   //
 219 
 220   ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
 221   initialize_reserved_region(heap_rs);
 222   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
 223   _heap_region_special = heap_rs.special();
 224 
 225   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 226          "Misaligned heap: " PTR_FORMAT, p2i(base()));
 227   os::trace_page_sizes_for_requested_size("Heap",
 228                                           max_byte_size, heap_alignment,
 229                                           heap_rs.base(),
 230                                           heap_rs.size(), heap_rs.page_size());
 231 
 232 #if SHENANDOAH_OPTIMIZED_MARKTASK
 233   // The optimized ShenandoahMarkTask takes some bits away from the full object bits.
 234   // Fail if we ever attempt to address more than we can.
 235   if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) {
 236     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
 237                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
 238                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
 239                 p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable());
 240     vm_exit_during_initialization("Fatal Error", buf);
 241   }
 242 #endif
 243 
 244   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
 245   if (!_heap_region_special) {
 246     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
 247                               "Cannot commit heap memory");
 248   }
 249 
 250   BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this, _heap_region));
 251 
 252   // Now we know the number of regions and heap sizes, initialize the heuristics.
 253   initialize_heuristics();
 254 
 255   // If ShenandoahCardBarrier is enabled but it's not generational mode
 256   // it means we're under passive mode and we have to initialize old gen
 257   // for the purpose of having card table.
 258   if (ShenandoahCardBarrier && !(mode()->is_generational())) {
 259     _old_generation = new ShenandoahOldGeneration(max_workers());
 260   }
 261 
 262   assert(_heap_region.byte_size() == heap_rs.size(), "Need to know reserved size for card table");
 263 
 264   //
 265   // Worker threads must be initialized after the barrier is configured
 266   //
 267   _workers = new ShenandoahWorkerThreads("ShenWorker", _max_workers);
 268   if (_workers == nullptr) {
 269     vm_exit_during_initialization("Failed necessary allocation.");
 270   } else {
 271     _workers->initialize_workers();
 272   }
 273 
 274   if (ParallelGCThreads > 1) {
 275     _safepoint_workers = new ShenandoahWorkerThreads("Safepoint Cleanup Thread", ParallelGCThreads);
 276     _safepoint_workers->initialize_workers();
 277   }
 278 
 279   //
 280   // Reserve and commit memory for bitmap(s)
 281   //
 282 
 283   size_t bitmap_size_orig = ShenandoahMarkBitMap::compute_size(heap_rs.size());
 284   _bitmap_size = align_up(bitmap_size_orig, bitmap_page_size);
 285 
 286   size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor();
 287 
 288   guarantee(bitmap_bytes_per_region != 0,
 289             "Bitmap bytes per region should not be zero");
 290   guarantee(is_power_of_2(bitmap_bytes_per_region),
 291             "Bitmap bytes per region should be power of two: %zu", bitmap_bytes_per_region);
 292 
 293   if (bitmap_page_size > bitmap_bytes_per_region) {
 294     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
 295     _bitmap_bytes_per_slice = bitmap_page_size;
 296   } else {
 297     _bitmap_regions_per_slice = 1;
 298     _bitmap_bytes_per_slice = bitmap_bytes_per_region;
 299   }
 300 
 301   guarantee(_bitmap_regions_per_slice >= 1,
 302             "Should have at least one region per slice: %zu",
 303             _bitmap_regions_per_slice);
 304 
 305   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
 306             "Bitmap slices should be page-granular: bps = %zu, page size = %zu",
 307             _bitmap_bytes_per_slice, bitmap_page_size);
 308 
 309   ReservedSpace bitmap = reserve(_bitmap_size, bitmap_page_size);
 310   os::trace_page_sizes_for_requested_size("Mark Bitmap",
 311                                           bitmap_size_orig, bitmap_page_size,
 312                                           bitmap.base(),
 313                                           bitmap.size(), bitmap.page_size());
 314   MemTracker::record_virtual_memory_tag(bitmap, mtGC);
 315   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 316   _bitmap_region_special = bitmap.special();
 317 
 318   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
 319     align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
 320   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
 321   if (!_bitmap_region_special) {
 322     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
 323                               "Cannot commit bitmap memory");
 324   }
 325 
 326   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions);
 327 
 328   if (ShenandoahVerify) {
 329     ReservedSpace verify_bitmap = reserve(_bitmap_size, bitmap_page_size);
 330     os::trace_page_sizes_for_requested_size("Verify Bitmap",
 331                                             bitmap_size_orig, bitmap_page_size,
 332                                             verify_bitmap.base(),
 333                                             verify_bitmap.size(), verify_bitmap.page_size());
 334     if (!verify_bitmap.special()) {
 335       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
 336                                 "Cannot commit verification bitmap memory");
 337     }
 338     MemTracker::record_virtual_memory_tag(verify_bitmap, mtGC);
 339     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 340     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 341     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 342   }
 343 
 344   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 345   size_t aux_bitmap_page_size = bitmap_page_size;
 346 
 347   ReservedSpace aux_bitmap = reserve(_bitmap_size, aux_bitmap_page_size);
 348   os::trace_page_sizes_for_requested_size("Aux Bitmap",
 349                                           bitmap_size_orig, aux_bitmap_page_size,
 350                                           aux_bitmap.base(),
 351                                           aux_bitmap.size(), aux_bitmap.page_size());
 352   MemTracker::record_virtual_memory_tag(aux_bitmap, mtGC);
 353   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 354   _aux_bitmap_region_special = aux_bitmap.special();
 355   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 356 
 357   //
 358   // Create regions and region sets
 359   //
 360   size_t region_align = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);
 361   size_t region_storage_size_orig = region_align * _num_regions;
 362   size_t region_storage_size = align_up(region_storage_size_orig,
 363                                         MAX2(region_page_size, os::vm_allocation_granularity()));
 364 
 365   ReservedSpace region_storage = reserve(region_storage_size, region_page_size);
 366   os::trace_page_sizes_for_requested_size("Region Storage",
 367                                           region_storage_size_orig, region_page_size,
 368                                           region_storage.base(),
 369                                           region_storage.size(), region_storage.page_size());
 370   MemTracker::record_virtual_memory_tag(region_storage, mtGC);
 371   if (!region_storage.special()) {
 372     os::commit_memory_or_exit(region_storage.base(), region_storage_size, region_page_size, false,
 373                               "Cannot commit region memory");
 374   }
 375 
 376   // Try to fit the collection set bitmap at lower addresses. This optimizes code generation for cset checks.
 377   // Go up until a sensible limit (subject to encoding constraints) and try to reserve the space there.
 378   // If not successful, bite a bullet and allocate at whatever address.
 379   {
 380     const size_t cset_align = MAX2<size_t>(os::vm_page_size(), os::vm_allocation_granularity());
 381     const size_t cset_size = align_up(((size_t) sh_rs.base() + sh_rs.size()) >> ShenandoahHeapRegion::region_size_bytes_shift(), cset_align);
 382     const size_t cset_page_size = os::vm_page_size();
 383 
 384     uintptr_t min = round_up_power_of_2(cset_align);
 385     uintptr_t max = (1u << 30u);
 386     ReservedSpace cset_rs;
 387 
 388     for (uintptr_t addr = min; addr <= max; addr <<= 1u) {
 389       char* req_addr = (char*)addr;
 390       assert(is_aligned(req_addr, cset_align), "Should be aligned");
 391       cset_rs = MemoryReserver::reserve(req_addr, cset_size, cset_align, cset_page_size, mtGC);
 392       if (cset_rs.is_reserved()) {
 393         assert(cset_rs.base() == req_addr, "Allocated where requested: " PTR_FORMAT ", " PTR_FORMAT, p2i(cset_rs.base()), addr);
 394         _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 395         break;
 396       }
 397     }
 398 
 399     if (_collection_set == nullptr) {
 400       cset_rs = MemoryReserver::reserve(cset_size, cset_align, os::vm_page_size(), mtGC);
 401       if (!cset_rs.is_reserved()) {
 402         vm_exit_during_initialization("Cannot reserve memory for collection set");
 403       }
 404 
 405       _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 406     }
 407     os::trace_page_sizes_for_requested_size("Collection Set",
 408                                             cset_size, cset_page_size,
 409                                             cset_rs.base(),
 410                                             cset_rs.size(), cset_rs.page_size());
 411   }
 412 
 413   _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
 414   _affiliations = NEW_C_HEAP_ARRAY(uint8_t, _num_regions, mtGC);
 415 
 416   {
 417     ShenandoahHeapLocker locker(lock());
 418     for (size_t i = 0; i < _num_regions; i++) {
 419       HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i;
 420       bool is_committed = i < num_committed_regions;
 421       void* loc = region_storage.base() + i * region_align;
 422 
 423       ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed);
 424       assert(is_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity");
 425 
 426       _marking_context->initialize_top_at_mark_start(r);
 427       _regions[i] = r;
 428       assert(!collection_set()->is_in(i), "New region should not be in collection set");
 429 
 430       _affiliations[i] = ShenandoahAffiliation::FREE;
 431     }
 432 
 433     if (mode()->is_generational()) {
 434       size_t young_reserve = (soft_max_capacity() * ShenandoahEvacReserve) / 100;
 435       young_generation()->set_evacuation_reserve(young_reserve);
 436       old_generation()->set_evacuation_reserve((size_t) 0);
 437       old_generation()->set_promoted_reserve((size_t) 0);
 438     }
 439 
 440     _free_set = new ShenandoahFreeSet(this, _num_regions);
 441     _allocator = new ShenandoahAllocator(_free_set);
 442     initialize_generations();
 443 
 444     // We are initializing free set.  We ignore cset region tallies.
 445     size_t young_trashed_regions, old_trashed_regions, first_old, last_old, num_old;
 446     _free_set->prepare_to_rebuild(young_trashed_regions, old_trashed_regions, first_old, last_old, num_old);
 447     if (mode()->is_generational()) {
 448       ShenandoahGenerationalHeap* gen_heap = ShenandoahGenerationalHeap::heap();
 449       // We cannot call
 450       //  gen_heap->young_generation()->heuristics()->bytes_of_allocation_runway_before_gc_trigger(young_cset_regions)
 451       // until after the heap is fully initialized.  So we make up a safe value here.
 452       size_t allocation_runway = InitialHeapSize / 2;
 453       // We're initializing the heap.  All regions within young are initially empty.
 454       size_t max_transfer = allocation_runway;
 455       gen_heap->compute_old_generation_balance(max_transfer, old_trashed_regions, young_trashed_regions);
 456     }
 457     _free_set->finish_rebuild(young_trashed_regions, old_trashed_regions, num_old);
 458   }
 459 
 460   if (AlwaysPreTouch) {
 461     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
 462     // before initialize() below zeroes it with initializing thread. For any given region,
 463     // we touch the region and the corresponding bitmaps from the same thread.
 464     ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
 465 
 466     _pretouch_heap_page_size = heap_page_size;
 467     _pretouch_bitmap_page_size = bitmap_page_size;
 468 
 469     // OS memory managers may want to coalesce back-to-back pages. Make their jobs
 470     // simpler by pre-touching continuous spaces (heap and bitmap) separately.
 471 
 472     ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, _pretouch_bitmap_page_size);
 473     _workers->run_task(&bcl);
 474 
 475     ShenandoahPretouchHeapTask hcl(_pretouch_heap_page_size);
 476     _workers->run_task(&hcl);
 477   }
 478 
 479   //
 480   // Initialize the rest of GC subsystems
 481   //
 482 
 483   _liveness_cache = NEW_C_HEAP_ARRAY(ShenandoahLiveData*, _max_workers, mtGC);
 484   for (uint worker = 0; worker < _max_workers; worker++) {
 485     _liveness_cache[worker] = NEW_C_HEAP_ARRAY(ShenandoahLiveData, _num_regions, mtGC);
 486     Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(ShenandoahLiveData));
 487   }
 488 
 489   // There should probably be Shenandoah-specific options for these,
 490   // just as there are G1-specific options.
 491   {
 492     ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
 493     satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
 494     satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
 495   }
 496 
 497   _monitoring_support = new ShenandoahMonitoringSupport(this);
 498   _phase_timings = new ShenandoahPhaseTimings(max_workers());
 499   ShenandoahCodeRoots::initialize();
 500 
 501   // Initialization of controller makes use of variables established by initialize_heuristics.
 502   initialize_controller();
 503 
 504   // Certain initialization of heuristics must be deferred until after controller is initialized.
 505   post_initialize_heuristics();
 506   start_idle_span();
 507   if (ShenandoahUncommit) {
 508     _uncommit_thread = new ShenandoahUncommitThread(this);
 509   }
 510   print_init_logger();
 511   FullGCForwarding::initialize(_heap_region);
 512   return JNI_OK;
 513 }
 514 
 515 void ShenandoahHeap::initialize_controller() {
 516   _control_thread = new ShenandoahControlThread();
 517 }
 518 
 519 void ShenandoahHeap::print_init_logger() const {
 520   ShenandoahInitLogger::print();
 521 }
 522 
 523 void ShenandoahHeap::initialize_mode() {
 524   if (ShenandoahGCMode != nullptr) {
 525     if (strcmp(ShenandoahGCMode, "satb") == 0) {
 526       _gc_mode = new ShenandoahSATBMode();
 527     } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
 528       _gc_mode = new ShenandoahPassiveMode();
 529     } else if (strcmp(ShenandoahGCMode, "generational") == 0) {
 530       _gc_mode = new ShenandoahGenerationalMode();
 531     } else {
 532       vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
 533     }
 534   } else {
 535     vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option (null)");
 536   }
 537   _gc_mode->initialize_flags();
 538   if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 539     vm_exit_during_initialization(
 540             err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 541                     _gc_mode->name()));
 542   }
 543   if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {
 544     vm_exit_during_initialization(
 545             err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 546                     _gc_mode->name()));
 547   }
 548 }
 549 
 550 void ShenandoahHeap::initialize_heuristics() {
 551   _global_generation = new ShenandoahGlobalGeneration(mode()->is_generational(), max_workers());
 552   _global_generation->initialize_heuristics(mode());
 553 }
 554 
 555 #ifdef _MSC_VER
 556 #pragma warning( push )
 557 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 558 #endif
 559 
 560 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 561   CollectedHeap(),
 562   _active_generation(nullptr),
 563   _initial_size(0),
 564   _committed(0),
 565   _alloc_rate_decay(&_alloc_rate),
 566   _max_workers(MAX3(ConcGCThreads, ParallelGCThreads, 1U)),
 567   _workers(nullptr),
 568   _safepoint_workers(nullptr),
 569   _heap_region_special(false),
 570   _num_regions(0),
 571   _regions(nullptr),
 572   _affiliations(nullptr),
 573   _gc_state_changed(false),
 574   _gc_no_progress_count(0),
 575   _cancel_requested_time(0),
 576   _update_refs_iterator(this),
 577   _global_generation(nullptr),
 578   _control_thread(nullptr),
 579   _uncommit_thread(nullptr),
 580   _young_generation(nullptr),
 581   _old_generation(nullptr),
 582   _shenandoah_policy(policy),
 583   _gc_mode(nullptr),
 584   _free_set(nullptr),
 585   _allocator(nullptr),
 586   _verifier(nullptr),
 587   _phase_timings(nullptr),
 588   _monitoring_support(nullptr),
 589   _memory_pool(nullptr),
 590   _stw_memory_manager("Shenandoah Pauses"),
 591   _cycle_memory_manager("Shenandoah Cycles"),
 592   _gc_timer(new ConcurrentGCTimer()),
 593   _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),
 594   _marking_context(nullptr),
 595   _bitmap_size(0),
 596   _bitmap_regions_per_slice(0),
 597   _bitmap_bytes_per_slice(0),
 598   _bitmap_region_special(false),
 599   _aux_bitmap_region_special(false),
 600   _liveness_cache(nullptr),
 601   _collection_set(nullptr),
 602   _evac_tracker(new ShenandoahEvacuationTracker()),
 603   _injected_pin_count(0)
 604 {
 605   // Initialize GC mode early, many subsequent initialization procedures depend on it
 606   initialize_mode();
 607   _cancelled_gc.set(GCCause::_no_gc);
 608 }
 609 
 610 #ifdef _MSC_VER
 611 #pragma warning( pop )
 612 #endif
 613 
 614 void ShenandoahHeap::print_heap_on(outputStream* st) const {
 615   const bool is_generational = mode()->is_generational();
 616   const char* front_spacing = "";
 617   if (is_generational) {
 618     st->print_cr("Generational Shenandoah Heap");
 619     st->print_cr(" Young:");
 620     st->print_cr("  " PROPERFMT " max, " PROPERFMT " used", PROPERFMTARGS(young_generation()->max_capacity()), PROPERFMTARGS(young_generation()->used()));
 621     st->print_cr(" Old:");
 622     st->print_cr("  " PROPERFMT " max, " PROPERFMT " used", PROPERFMTARGS(old_generation()->max_capacity()), PROPERFMTARGS(old_generation()->used()));
 623     st->print_cr(" Entire heap:");
 624     st->print_cr("  " PROPERFMT " soft max, " PROPERFMT " committed",
 625                 PROPERFMTARGS(soft_max_capacity()), PROPERFMTARGS(committed()));
 626     front_spacing = " ";
 627   } else {
 628     st->print_cr("Shenandoah Heap");
 629     st->print_cr("  " PROPERFMT " max, " PROPERFMT " soft max, " PROPERFMT " committed, " PROPERFMT " used",
 630       PROPERFMTARGS(max_capacity()),
 631       PROPERFMTARGS(soft_max_capacity()),
 632       PROPERFMTARGS(committed()),
 633       PROPERFMTARGS(used())
 634     );
 635   }
 636   st->print_cr("%s %zu x " PROPERFMT " regions",
 637           front_spacing,
 638           num_regions(),
 639           PROPERFMTARGS(ShenandoahHeapRegion::region_size_bytes()));
 640 
 641   st->print("Status: ");
 642   if (has_forwarded_objects())                 st->print("has forwarded objects, ");
 643   if (!is_generational) {
 644     if (is_concurrent_mark_in_progress())      st->print("marking,");
 645   } else {
 646     if (is_concurrent_old_mark_in_progress())    st->print("old marking, ");
 647     if (is_concurrent_young_mark_in_progress())  st->print("young marking, ");
 648   }
 649   if (is_evacuation_in_progress())             st->print("evacuating, ");
 650   if (is_update_refs_in_progress())            st->print("updating refs, ");
 651   if (is_degenerated_gc_in_progress())         st->print("degenerated gc, ");
 652   if (is_full_gc_in_progress())                st->print("full gc, ");
 653   if (is_full_gc_move_in_progress())           st->print("full gc move, ");
 654   if (is_concurrent_weak_root_in_progress())   st->print("concurrent weak roots, ");
 655   if (is_concurrent_strong_root_in_progress() &&
 656       !is_concurrent_weak_root_in_progress())  st->print("concurrent strong roots, ");
 657 
 658   if (cancelled_gc()) {
 659     st->print("cancelled");
 660   } else {
 661     st->print("not cancelled");
 662   }
 663   st->cr();
 664 
 665   st->print_cr("Reserved region:");
 666   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
 667                p2i(reserved_region().start()),
 668                p2i(reserved_region().end()));
 669 
 670   ShenandoahCollectionSet* cset = collection_set();
 671   st->print_cr("Collection set:");
 672   if (cset != nullptr) {
 673     st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));
 674     st->print_cr(" - map (biased):  " PTR_FORMAT, p2i(cset->biased_map_address()));
 675   } else {
 676     st->print_cr(" (null)");
 677   }
 678 
 679   st->cr();
 680 
 681   if (Verbose) {
 682     st->cr();
 683     print_heap_regions_on(st);
 684   }
 685 }
 686 
 687 void ShenandoahHeap::print_gc_on(outputStream* st) const {
 688   print_heap_regions_on(st);
 689 }
 690 
 691 class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {
 692 public:
 693   void do_thread(Thread* thread) {
 694     assert(thread != nullptr, "Sanity");
 695     ShenandoahThreadLocalData::initialize_gclab(thread);
 696   }
 697 };
 698 
 699 void ShenandoahHeap::initialize_generations() {
 700   _global_generation->post_initialize(this);
 701 }
 702 
 703 // We do not call this explicitly  It is called by Hotspot infrastructure.
 704 void ShenandoahHeap::post_initialize() {
 705   CollectedHeap::post_initialize();
 706 
 707   check_soft_max_changed();
 708 
 709   // Schedule periodic task to report on gc thread CPU utilization
 710   _mmu_tracker.initialize();
 711 
 712   // Periodically decay allocation rate to compensate for not being updated when allocation rate
 713   // is low. Heuristics are evaluated unconditionally from a dedicated thread so it will continue
 714   // to see the last (possibly stale) allocation rate if the allocation rate is low.
 715   _alloc_rate_decay.enroll();
 716 
 717   MutexLocker ml(Threads_lock);
 718 
 719   ShenandoahInitWorkerGCLABClosure init_gclabs;
 720   _workers->threads_do(&init_gclabs);
 721 
 722   // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 723   // Now, we will let WorkerThreads to initialize gclab when new worker is created.
 724   _workers->set_initialize_gclab();
 725 
 726   // Note that the safepoint workers may require gclabs if the threads are used to create a heap dump
 727   // during a concurrent evacuation phase.
 728   if (_safepoint_workers != nullptr) {
 729     _safepoint_workers->threads_do(&init_gclabs);
 730     _safepoint_workers->set_initialize_gclab();
 731   }
 732 
 733   JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers();)
 734 }
 735 
 736 void ShenandoahHeap::post_initialize_heuristics() {
 737   _global_generation->post_initialize_heuristics();
 738 }
 739 
 740 ShenandoahHeuristics* ShenandoahHeap::heuristics() {
 741   return _global_generation->heuristics();
 742 }
 743 
 744 size_t ShenandoahHeap::used() const {
 745   return global_generation()->used();
 746 }
 747 
 748 size_t ShenandoahHeap::committed() const {
 749   return _committed.load_relaxed();
 750 }
 751 
 752 void ShenandoahHeap::increase_committed(size_t bytes) {
 753   shenandoah_assert_heaplocked_or_safepoint();
 754   _committed.fetch_then_add(bytes, memory_order_relaxed);
 755 }
 756 
 757 void ShenandoahHeap::decrease_committed(size_t bytes) {
 758   shenandoah_assert_heaplocked_or_safepoint();
 759   _committed.fetch_then_sub(bytes, memory_order_relaxed);
 760 }
 761 
 762 size_t ShenandoahHeap::capacity() const {
 763   return committed();
 764 }
 765 
 766 size_t ShenandoahHeap::max_capacity() const {
 767   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 768 }
 769 
 770 size_t ShenandoahHeap::soft_max_capacity() const {
 771   size_t v = _soft_max_size.load_relaxed();
 772   assert(min_capacity() <= v && v <= max_capacity(),
 773          "Should be in bounds: %zu <= %zu <= %zu",
 774          min_capacity(), v, max_capacity());
 775   return v;
 776 }
 777 
 778 void ShenandoahHeap::set_soft_max_capacity(size_t v) {
 779   assert(min_capacity() <= v && v <= max_capacity(),
 780          "Should be in bounds: %zu <= %zu <= %zu",
 781          min_capacity(), v, max_capacity());
 782   _soft_max_size.store_relaxed(v);
 783   heuristics()->compute_headroom_adjustment();
 784 }
 785 
 786 size_t ShenandoahHeap::min_capacity() const {
 787   return _minimum_size;
 788 }
 789 
 790 size_t ShenandoahHeap::initial_capacity() const {
 791   return _initial_size;
 792 }
 793 
 794 bool ShenandoahHeap::is_in(const void* p) const {
 795   if (!is_in_reserved(p)) {
 796     return false;
 797   }
 798 
 799   if (is_full_gc_move_in_progress()) {
 800     // Full GC move is running, we do not have a consistent region
 801     // information yet. But we know the pointer is in heap.
 802     return true;
 803   }
 804 
 805   // Now check if we point to a live section in active region.
 806   const ShenandoahHeapRegion* r = heap_region_containing(p);
 807   if (p >= r->top()) {
 808     return false;
 809   }
 810 
 811   if (r->is_active()) {
 812     return true;
 813   }
 814 
 815   // The region is trash, but won't be recycled until after concurrent weak
 816   // roots. We also don't allow mutators to allocate from trash regions
 817   // during weak roots. Concurrent class unloading may access unmarked oops
 818   // in trash regions.
 819   return r->is_trash() && is_concurrent_weak_root_in_progress();
 820 }
 821 
 822 void ShenandoahHeap::notify_soft_max_changed() {
 823   if (_uncommit_thread != nullptr) {
 824     _uncommit_thread->notify_soft_max_changed();
 825   }
 826 }
 827 
 828 void ShenandoahHeap::notify_explicit_gc_requested() {
 829   if (_uncommit_thread != nullptr) {
 830     _uncommit_thread->notify_explicit_gc_requested();
 831   }
 832 }
 833 
 834 bool ShenandoahHeap::check_soft_max_changed() {
 835   size_t new_soft_max = AtomicAccess::load(&SoftMaxHeapSize);
 836   size_t old_soft_max = soft_max_capacity();
 837   if (new_soft_max != old_soft_max) {
 838     new_soft_max = clamp(new_soft_max, min_capacity(), max_capacity());
 839     if (new_soft_max != old_soft_max) {
 840       log_info(gc)("Soft Max Heap Size: %zu%s -> %zu%s",
 841                    byte_size_in_proper_unit(old_soft_max), proper_unit_for_byte_size(old_soft_max),
 842                    byte_size_in_proper_unit(new_soft_max), proper_unit_for_byte_size(new_soft_max)
 843       );
 844       set_soft_max_capacity(new_soft_max);
 845       return true;
 846     }
 847   }
 848   return false;
 849 }
 850 
 851 void ShenandoahHeap::notify_heap_changed() {
 852   // Update monitoring counters when we took a new region. This amortizes the
 853   // update costs on slow path.
 854   monitoring_support()->notify_heap_changed();
 855   _heap_changed.try_set();
 856 }
 857 
 858 void ShenandoahHeap::start_idle_span() {
 859   heuristics()->start_idle_span();
 860 }
 861 
 862 void ShenandoahHeap::set_forced_counters_update(bool value) {
 863   monitoring_support()->set_forced_counters_update(value);
 864 }
 865 
 866 void ShenandoahHeap::handle_force_counters_update() {
 867   monitoring_support()->handle_force_counters_update();
 868 }
 869 
 870 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 871   // New object should fit the GCLAB size
 872   size_t min_size = MAX2(size, PLAB::min_size());
 873 
 874   // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
 875   size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
 876 
 877   new_size = MIN2(new_size, PLAB::max_size());
 878   new_size = MAX2(new_size, PLAB::min_size());
 879 
 880   // Record new heuristic value even if we take any shortcut. This captures
 881   // the case when moderately-sized objects always take a shortcut. At some point,
 882   // heuristics should catch up with them.
 883   log_debug(gc, free)("Set new GCLAB size: %zu", new_size);
 884   ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
 885 
 886   if (new_size < size) {
 887     // New size still does not fit the object. Fall back to shared allocation.
 888     // This avoids retiring perfectly good GCLABs, when we encounter a large object.
 889     log_debug(gc, free)("New gclab size (%zu) is too small for %zu", new_size, size);
 890     return nullptr;
 891   }
 892 
 893   // Retire current GCLAB, and allocate a new one.
 894   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
 895   gclab->retire();
 896 
 897   size_t actual_size = 0;
 898   HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);
 899   if (gclab_buf == nullptr) {
 900     return nullptr;
 901   }
 902 
 903   assert (size <= actual_size, "allocation should fit");
 904 
 905   // ...and clear or zap just allocated TLAB, if needed.
 906   if (ZeroTLAB) {
 907     Copy::zero_to_words(gclab_buf, actual_size);
 908   } else if (ZapTLAB) {
 909     // Skip mangling the space corresponding to the object header to
 910     // ensure that the returned space is not considered parsable by
 911     // any concurrent GC thread.
 912     size_t hdr_size = oopDesc::header_size();
 913     Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 914   }
 915   gclab->set_buf(gclab_buf, actual_size);
 916   return gclab->allocate(size);
 917 }
 918 
 919 // Called from stubs in JIT code or interpreter
 920 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
 921                                             size_t requested_size,
 922                                             size_t* actual_size) {
 923   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
 924   HeapWord* res = allocate_memory(req);
 925   if (res != nullptr) {
 926     *actual_size = req.actual_size();
 927   } else {
 928     *actual_size = 0;
 929   }
 930   return res;
 931 }
 932 
 933 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
 934                                              size_t word_size,
 935                                              size_t* actual_size) {
 936   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
 937   HeapWord* res = allocate_memory(req);
 938   if (res != nullptr) {
 939     *actual_size = req.actual_size();
 940   } else {
 941     *actual_size = 0;
 942   }
 943   return res;
 944 }
 945 
 946 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {
 947   bool in_new_region = false;
 948   HeapWord* result = nullptr;
 949 
 950   if (req.is_mutator_alloc()) {
 951 
 952     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
 953       result = allocate_memory_work(req, in_new_region);
 954     }
 955 
 956     // Check that gc overhead is not exceeded.
 957     //
 958     // Shenandoah will grind along for quite a while allocating one
 959     // object at a time using shared (non-tlab) allocations. This check
 960     // is testing that the GC overhead limit has not been exceeded.
 961     // This will notify the collector to start a cycle, but will raise
 962     // an OOME to the mutator if the last Full GCs have not made progress.
 963     // gc_no_progress_count is incremented following each degen or full GC that fails to achieve is_good_progress().
 964     if (result == nullptr && !req.is_lab_alloc() && get_gc_no_progress_count() > ShenandoahNoProgressThreshold) {
 965       control_thread()->handle_alloc_failure(req, false);
 966       req.set_actual_size(0);
 967       return nullptr;
 968     }
 969 
 970     if (result == nullptr) {
 971       // Block until control thread reacted, then retry allocation.
 972       //
 973       // It might happen that one of the threads requesting allocation would unblock
 974       // way later after GC happened, only to fail the second allocation, because
 975       // other threads have already depleted the free storage. In this case, a better
 976       // strategy is to try again, until at least one full GC has completed.
 977       //
 978       // Stop retrying and return nullptr to cause OOMError exception if our allocation failed even after:
 979       //   a) We experienced a GC that had good progress, or
 980       //   b) We experienced at least one Full GC (whether or not it had good progress)
 981 
 982       const size_t original_count = shenandoah_policy()->full_gc_count();
 983       while (result == nullptr && should_retry_allocation(original_count)) {
 984         control_thread()->handle_alloc_failure(req, true);
 985         result = allocate_memory_work(req, in_new_region);
 986       }
 987       if (result != nullptr) {
 988         // If our allocation request has been satisfied after it initially failed, we count this as good gc progress
 989         notify_gc_progress();
 990       }
 991       if (log_develop_is_enabled(Debug, gc, alloc)) {
 992         ResourceMark rm;
 993         log_debug(gc, alloc)("Thread: %s, Result: " PTR_FORMAT ", Request: %s, Size: %zu"
 994                              ", Original: %zu, Latest: %zu",
 995                              Thread::current()->name(), p2i(result), req.type_string(), req.size(),
 996                              original_count, get_gc_no_progress_count());
 997       }
 998     }
 999   } else {
1000     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
1001     result = allocate_memory_work(req, in_new_region);
1002     // Do not call handle_alloc_failure() here, because we cannot block.
1003     // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
1004   }
1005 
1006   if (in_new_region) {
1007     notify_heap_changed();
1008   }
1009 
1010   if (result == nullptr) {
1011     req.set_actual_size(0);
1012   }
1013 
1014   if (result != nullptr) {
1015     size_t requested = req.size();
1016     size_t actual = req.actual_size();
1017 
1018     assert (req.is_lab_alloc() || (requested == actual),
1019             "Only LAB allocations are elastic: %s, requested = %zu, actual = %zu",
1020             req.type_string(), requested, actual);
1021   }
1022 
1023   return result;
1024 }
1025 
1026 inline bool ShenandoahHeap::should_retry_allocation(size_t original_full_gc_count) const {
1027   return shenandoah_policy()->full_gc_count() == original_full_gc_count
1028       && !shenandoah_policy()->is_at_shutdown();
1029 }
1030 
1031 HeapWord* ShenandoahHeap::allocate_memory_work(ShenandoahAllocRequest& req, bool& in_new_region) {
1032   // Reserve the promotion budget up front so it is enforced atomically without the heap lock.
1033   // If the reserve is exhausted, deny the promotion rather than overshoot it; the reservation
1034   // is refunded below if the allocation itself fails.
1035   if (req.is_promotion() && !old_generation()->try_expend_promoted(req.size() << LogHeapWordSize)) {
1036     return nullptr;
1037   }
1038 
1039   HeapWord* result = _allocator->allocate(req, in_new_region);
1040 
1041   if (result != nullptr) {
1042     if (req.is_mutator_alloc()) {
1043       _alloc_rate.allocated((req.actual_size() + req.waste()) * HeapWordSize);
1044     }
1045 
1046     if (req.is_old()) {
1047       if (req.is_lab_alloc()) {
1048         old_generation()->configure_plab_for_current_thread(req);
1049       } else if (req.is_promotion()) {
1050         log_debug(gc, plab)("Expend shared promotion of %zu bytes", req.actual_size() * HeapWordSize);
1051       }
1052     }
1053   } else if (req.is_promotion()) {
1054     // Allocation failed, so refund the promotion budget reserved above.
1055     old_generation()->unexpend_promoted(req.size() << LogHeapWordSize);
1056   }
1057   return result;
1058 }
1059 
1060 HeapWord* ShenandoahHeap::mem_allocate(size_t size) {
1061   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
1062   return allocate_memory(req);
1063 }
1064 
1065 oop ShenandoahHeap::array_allocate(Klass* klass, size_t size, int length, bool do_zero, TRAPS) {
1066   ShenandoahObjArrayAllocator allocator(klass, size, length, do_zero, THREAD);
1067   return allocator.allocate();
1068 }
1069 
1070 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
1071                                                              size_t size,
1072                                                              Metaspace::MetadataType mdtype) {
1073   MetaWord* result;
1074 
1075   // Inform metaspace OOM to GC heuristics if class unloading is possible.
1076   ShenandoahHeuristics* h = global_generation()->heuristics();
1077   if (h->can_unload_classes()) {
1078     h->record_metaspace_oom();
1079   }
1080 
1081   // Expand and retry allocation
1082   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
1083   if (result != nullptr) {
1084     return result;
1085   }
1086 
1087   // Start full GC
1088   collect(GCCause::_metadata_GC_clear_soft_refs);
1089 
1090   // Retry allocation
1091   result = loader_data->metaspace_non_null()->allocate(size, mdtype);
1092   if (result != nullptr) {
1093     return result;
1094   }
1095 
1096   // Expand and retry allocation
1097   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
1098   if (result != nullptr) {
1099     return result;
1100   }
1101 
1102   // Out of memory
1103   return nullptr;
1104 }
1105 
1106 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
1107 private:
1108   ShenandoahHeap* const _heap;
1109   Thread* const _thread;
1110 public:
1111   ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
1112     _heap(heap), _thread(Thread::current()) {}
1113 
1114   void do_object(oop p) {
1115     shenandoah_assert_marked(nullptr, p);
1116     if (!p->is_forwarded()) {
1117       _heap->evacuate_object(p, _thread);
1118     }
1119   }
1120 };
1121 
1122 class ShenandoahEvacuationTask : public WorkerTask {
1123 private:
1124   ShenandoahHeap* const _sh;
1125   ShenandoahCollectionSet* const _cs;
1126   bool _concurrent;
1127 public:
1128   ShenandoahEvacuationTask(ShenandoahHeap* sh,
1129                            ShenandoahCollectionSet* cs,
1130                            bool concurrent) :
1131     WorkerTask("Shenandoah Evacuation"),
1132     _sh(sh),
1133     _cs(cs),
1134     _concurrent(concurrent)
1135   {}
1136 
1137   void work(uint worker_id) {
1138     if (_concurrent) {
1139       ShenandoahWorkerTimingsTracker timer(ShenandoahPhaseTimings::conc_evac, ShenandoahPhaseTimings::Work, worker_id, true);
1140       ShenandoahConcurrentWorkerSession worker_session(worker_id);
1141       SuspendibleThreadSetJoiner stsj;
1142       do_work();
1143     } else {
1144       ShenandoahWorkerTimingsTracker timer(ShenandoahPhaseTimings::degen_gc_evac, ShenandoahPhaseTimings::Work, worker_id, true);
1145       ShenandoahParallelWorkerSession worker_session(worker_id);
1146       do_work();
1147     }
1148   }
1149 
1150 private:
1151   void do_work() {
1152     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
1153     ShenandoahHeapRegion* r;
1154     while ((r =_cs->claim_next()) != nullptr) {
1155       assert(r->has_live(), "Region %zu should have been reclaimed early", r->index());
1156       _sh->marked_object_iterate(r, &cl);
1157 
1158       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
1159         break;
1160       }
1161     }
1162   }
1163 };
1164 
1165 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1166 private:
1167   bool const _resize;
1168 public:
1169   explicit ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {}
1170   void do_thread(Thread* thread) override {
1171     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1172     assert(gclab != nullptr, "GCLAB should be initialized for %s", thread->name());
1173     gclab->retire();
1174     if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1175       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1176     }
1177 
1178     if (ShenandoahHeap::heap()->mode()->is_generational()) {
1179       ShenandoahPLAB* shenandoah_plab = ShenandoahThreadLocalData::shenandoah_plab(thread);
1180       assert(shenandoah_plab != nullptr, "PLAB should be initialized for %s", thread->name());
1181 
1182       // There are two reasons to retire all plabs between old-gen evacuation passes.
1183       //  1. We need to make the plab memory parsable by remembered-set scanning.
1184       //  2. We need to establish a trustworthy UpdateWaterMark value within each old-gen heap region
1185       shenandoah_plab->retire();
1186 
1187       // Re-enable promotions for the next evacuation phase.
1188       shenandoah_plab->enable_promotions();
1189 
1190       // Reset the fill size for next evacuation phase.
1191       if (_resize && shenandoah_plab->desired_size() > 0) {
1192         shenandoah_plab->set_desired_size(0);
1193       }
1194     }
1195   }
1196 };
1197 
1198 class ShenandoahGCStatePropagatorHandshakeClosure : public HandshakeClosure {
1199 public:
1200   explicit ShenandoahGCStatePropagatorHandshakeClosure(char gc_state) :
1201     HandshakeClosure("Shenandoah GC State Change"),
1202     _gc_state(gc_state) {}
1203 
1204   void do_thread(Thread* thread) override {
1205     ShenandoahThreadLocalData::set_gc_state(thread, _gc_state);
1206   }
1207 private:
1208   char _gc_state;
1209 };
1210 
1211 class ShenandoahPrepareForUpdateRefsHandshakeClosure : public HandshakeClosure {
1212 public:
1213   explicit ShenandoahPrepareForUpdateRefsHandshakeClosure(char gc_state) :
1214     HandshakeClosure("Shenandoah Prepare for Update Refs"),
1215     _retire(ResizeTLAB), _propagator(gc_state) {}
1216 
1217   void do_thread(Thread* thread) override {
1218     _propagator.do_thread(thread);
1219     if (ShenandoahThreadLocalData::gclab(thread) != nullptr) {
1220       _retire.do_thread(thread);
1221     }
1222   }
1223 private:
1224   ShenandoahRetireGCLABClosure _retire;
1225   ShenandoahGCStatePropagatorHandshakeClosure _propagator;
1226 };
1227 
1228 void ShenandoahHeap::evacuate_collection_set(ShenandoahGeneration* generation, bool concurrent) {
1229   assert(generation->is_global(), "Only global generation expected here");
1230   ShenandoahEvacuationTask task(this, _collection_set, concurrent);
1231   workers()->run_task(&task);
1232 }
1233 
1234 class ShenandoahCompleteStackWatermarkHandshakeClosure : public HandshakeClosure {
1235 public:
1236   ShenandoahCompleteStackWatermarkHandshakeClosure() : HandshakeClosure("Shenandoah Complete stacks handshake") {}
1237   void do_thread(Thread* thread) override {
1238     if (thread->is_Java_thread()) {
1239       JavaThread* jt = JavaThread::cast(thread);
1240       StackWatermarkSet::finish_processing(jt, nullptr, StackWatermarkKind::gc);
1241     }
1242   }
1243 };
1244 
1245 void ShenandoahHeap::concurrent_prepare_for_update_refs() {
1246   // The stack watermarks are active since op_final_roots().
1247   // Make sure the current stack watermark machinery has completed before we drop evac flags.
1248   // Otherwise the stack processing on stack unwinding may enter evac closure concurrently.
1249   ShenandoahCompleteStackWatermarkHandshakeClosure cl;
1250   Handshake::execute(&cl);
1251 
1252   {
1253     // Java threads take this lock while they are being attached and added to the list of threads.
1254     // If another thread holds this lock before we update the gc state, it will receive a stale
1255     // gc state, but they will have been added to the list of java threads and so will be corrected
1256     // by the following handshake.
1257     MutexLocker lock(Threads_lock);
1258 
1259     // A cancellation at this point means the degenerated cycle must resume from update-refs.
1260     set_gc_state_concurrent(EVACUATION, false);
1261     set_gc_state_concurrent(UPDATE_REFS, true);
1262   }
1263 
1264   // This will propagate the gc state and retire gclabs and plabs for threads that require it.
1265   ShenandoahPrepareForUpdateRefsHandshakeClosure prepare_for_update_refs(_gc_state.raw_value());
1266 
1267   // The handshake won't touch worker threads (or control thread, or VM thread), so do those separately.
1268   Threads::non_java_threads_do(&prepare_for_update_refs);
1269 
1270   // Now retire gclabs and plabs and propagate gc_state for mutator threads
1271   Handshake::execute(&prepare_for_update_refs);
1272 
1273   _update_refs_iterator.reset();
1274 }
1275 
1276 void ShenandoahHeap::op_final_roots() {
1277 #ifdef ASSERT
1278   // Check if stack watermark machinery is in safe state:
1279   //  1. With evac-in-progress, we are about to supersede evac processing with new epoch.
1280   //     op_thread_roots() should have completed the stack watermark processing before
1281   //     we reach here.
1282   //  2. Without evac-in-progress, we are in abbreviated cycle, and we are switching
1283   //     to a new epoch that *also* does not change any oops, which is safe.
1284   if (is_evacuation_in_progress()) {
1285     for (JavaThreadIteratorWithHandle jtiwh; JavaThread* jt = jtiwh.next();) {
1286       StackWatermark* sw = StackWatermarkSet::get(jt, StackWatermarkKind::gc);
1287       assert(sw == nullptr || sw->processing_completed(),
1288              "Cannot turn off weak roots before stack watermark processing is complete");
1289     }
1290   }
1291 #endif
1292 
1293   set_gc_state_at_safepoint(WEAK_ROOTS, false);
1294 
1295   // Arm the nmethods to change the barriers.
1296   CodeCache::arm_all_nmethods();
1297 
1298   {
1299     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_roots_propagate_gc_state);
1300     propagate_gc_state_to_all_threads();
1301   }
1302 }
1303 
1304 oop ShenandoahHeap::evacuate_object(oop p, Thread* thread) {
1305   assert(thread == Thread::current(), "Expected thread parameter to be current thread.");
1306 
1307   ShenandoahHeapRegion* r = heap_region_containing(p);
1308   assert(!r->is_humongous(), "never evacuate humongous objects");
1309 
1310   ShenandoahAffiliation target_gen = r->affiliation();
1311   return try_evacuate_object(p, thread, r, target_gen);
1312 }
1313 
1314 oop ShenandoahHeap::try_evacuate_object(oop p, Thread* thread, ShenandoahHeapRegion* from_region,
1315                                                ShenandoahAffiliation target_gen) {
1316   assert(target_gen == YOUNG_GENERATION, "Only expect evacuations to young in this mode");
1317   assert(from_region->is_young(), "Only expect evacuations from young in this mode");
1318   bool alloc_from_lab = true;
1319   HeapWord* copy = nullptr;
1320   size_t size = ShenandoahForwarding::size(p);
1321 
1322 #ifdef ASSERT
1323   if (ShenandoahOOMDuringEvacALot &&
1324       (os::random() & 1) == 0) { // Simulate OOM every ~2nd slow-path call
1325     copy = nullptr;
1326   } else {
1327 #endif
1328     if (UseTLAB) {
1329       copy = allocate_from_gclab(thread, size);
1330     }
1331     if (copy == nullptr) {
1332       // If we failed to allocate in LAB, we'll try a shared allocation.
1333       ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared_gc(size, target_gen);
1334       copy = allocate_memory(req);
1335       alloc_from_lab = false;
1336     }
1337 #ifdef ASSERT
1338   }
1339 #endif
1340 
1341   if (copy == nullptr) {
1342     control_thread()->handle_alloc_failure_evac(size);
1343 
1344     // Install the self-forwarded bit on p so other evacuators/LRBs see
1345     // the object as "already handled, do not try to evacuate". The CAS
1346     // may fail if another thread concurrently installed a real forwardee
1347     // (they succeeded where we failed) or self-forwarded first.
1348     markWord old_mark = p->mark();
1349     if (old_mark.is_forwarded()) {
1350       return ShenandoahForwarding::get_forwardee(p);
1351     }
1352     oop winner = ShenandoahForwarding::try_forward_to_self(p, old_mark);
1353     if (winner == nullptr) {
1354       // We own the self-forwarding. Flag the region so the degen/full GC
1355       // entry drain knows to scan it for self_fwd bits to clear.
1356       from_region->set_has_self_forwards();
1357       return p;
1358     }
1359     return winner;
1360   }
1361 
1362   if (ShenandoahEvacTracking) {
1363     evac_tracker()->begin_evacuation(thread, size * HeapWordSize, from_region->affiliation(), target_gen);
1364   }
1365 
1366   // Copy the object:
1367   Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(p), copy, size);
1368 
1369   oop copy_val = cast_to_oop(copy);
1370 
1371   // Relativize stack chunks before publishing the copy. After the forwarding CAS,
1372   // mutators can see the copy and thaw it via the fast path if flags == 0. We must
1373   // relativize derived pointers and set gc_mode before that happens. Skip if the
1374   // copy's mark word is already a forwarding pointer (another thread won the race
1375   // and overwrote the original's header before we copied it).
1376   if (!ShenandoahForwarding::is_forwarded(copy_val)) {
1377     ContinuationGCSupport::relativize_stack_chunk(copy_val);
1378   }
1379 
1380   // Try to install the new forwarding pointer.
1381   oop result = ShenandoahForwarding::try_update_forwardee(p, copy_val);
1382   if (result == copy_val) {
1383     // Successfully evacuated. Our copy is now the public one!
1384     shenandoah_assert_correct(nullptr, copy_val);
1385     if (ShenandoahEvacTracking) {
1386       evac_tracker()->end_evacuation(thread, size * HeapWordSize, from_region->affiliation(), target_gen);
1387     }
1388     return copy_val;
1389   }  else {
1390     // Failed to evacuate. We need to deal with the object that is left behind. Since this
1391     // new allocation is certainly after TAMS, it will be considered live in the next cycle.
1392     // But if it happens to contain references to evacuated regions, those references would
1393     // not get updated for this stale copy during this cycle, and we will crash while scanning
1394     // it the next cycle.
1395     if (alloc_from_lab) {
1396       // For LAB allocations, it is enough to rollback the allocation ptr. Either the next
1397       // object will overwrite this stale copy, or the filler object on LAB retirement will
1398       // do this.
1399       ShenandoahThreadLocalData::gclab(thread)->undo_allocation(copy, size);
1400     } else {
1401       // For non-LAB allocations, we have no way to retract the allocation, and
1402       // have to explicitly overwrite the copy with the filler object. With that overwrite,
1403       // we have to keep the fwdptr initialized and pointing to our (stale) copy.
1404       assert(size >= ShenandoahHeap::min_fill_size(), "previously allocated object known to be larger than min_size");
1405       fill_with_object(copy, size);
1406       shenandoah_assert_correct(nullptr, copy_val);
1407       // For non-LAB allocations, the object has already been registered
1408     }
1409     shenandoah_assert_correct(nullptr, result);
1410     return result;
1411   }
1412 }
1413 
1414 // Clear the self_fwd bit on a live cset object, if set. Runs at a safepoint,
1415 // so a plain store is sufficient — no concurrent writers to the mark word.
1416 class ShenandoahUnSelfForwardObjectClosure : public ObjectClosure {
1417 public:
1418   void do_object(oop obj) override {
1419     markWord m = obj->mark();
1420     if (m.is_self_forwarded()) {
1421       obj->set_mark(m.unset_self_forwarded());
1422     }
1423   }
1424 };
1425 
1426 // Parallel task over flagged cset regions. Iterates the live objects via the
1427 // mark bitmap (skipping evacuated and never-marked memory), clears self_fwd
1428 // bits, and resets the region flag once done.
1429 class ShenandoahUnSelfForwardTask : public WorkerTask {
1430 private:
1431   ShenandoahHeap*          const _heap;
1432   ShenandoahCollectionSet* const _cs;
1433 
1434 public:
1435   ShenandoahUnSelfForwardTask(ShenandoahHeap* heap, ShenandoahCollectionSet* cs) :
1436     WorkerTask("Shenandoah Un-Self-Forward"),
1437     _heap(heap),
1438     _cs(cs) {}
1439 
1440   void work(uint worker_id) override {
1441     ShenandoahParallelWorkerSession worker_session(worker_id);
1442     ShenandoahUnSelfForwardObjectClosure cl;
1443     ShenandoahHeapRegion* r;
1444     while ((r = _cs->claim_next()) != nullptr) {
1445       if (r->has_self_forwards()) {
1446         _heap->marked_object_iterate(r, &cl);
1447         r->clear_has_self_forwards();
1448       }
1449     }
1450   }
1451 };
1452 
1453 void ShenandoahHeap::un_self_forward_cset_regions() {
1454   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
1455   ShenandoahCollectionSet* cs = collection_set();
1456   if (cs == nullptr || cs->is_empty()) {
1457     return;
1458   }
1459   cs->clear_current_index();
1460   ShenandoahUnSelfForwardTask task(this, cs);
1461   workers()->run_task(&task);
1462   DEBUG_ONLY(assert_no_self_forwards());
1463 }
1464 
1465 #ifdef ASSERT
1466 void ShenandoahHeap::assert_no_self_forwards() const {
1467   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
1468   ShenandoahCollectionSet* cs = collection_set();
1469   if (cs == nullptr) return;
1470   cs->clear_current_index();
1471   ShenandoahHeapRegion* r;
1472   while ((r = cs->next()) != nullptr) {
1473     assert(!r->has_self_forwards(), "region still flagged after drain");
1474   }
1475   cs->clear_current_index();
1476 }
1477 #endif
1478 
1479 void ShenandoahHeap::trash_cset_regions() {
1480   ShenandoahHeapLocker locker(lock());
1481 
1482   ShenandoahCollectionSet* set = collection_set();
1483   ShenandoahHeapRegion* r;
1484   set->clear_current_index();
1485   while ((r = set->next()) != nullptr) {
1486     r->make_trash();
1487   }
1488   collection_set()->clear();
1489 }
1490 
1491 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
1492   st->print_cr("Heap Regions:");
1493   st->print_cr("Region state: EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HP=pinned humongous start");
1494   st->print_cr("              HC=humongous continuation, CS=collection set, TR=trash, P=pinned, CSP=pinned collection set");
1495   st->print_cr("A=age, BTE=bottom/top/end, TAMS=top-at-mark-start, UWM=update watermark, U=used");
1496   st->print_cr("T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
1497   st->print_cr("CP=critical pins");
1498 
1499   for (size_t i = 0; i < num_regions(); i++) {
1500     get_region(i)->print_on(st);
1501   }
1502 }
1503 
1504 void ShenandoahHeap::process_gc_stats() const {
1505   // Commit worker statistics to cycle data
1506   phase_timings()->flush_par_workers_to_cycle();
1507 
1508   // Print GC stats for current cycle
1509   LogTarget(Info, gc, stats) lt;
1510   if (lt.is_enabled()) {
1511     ResourceMark rm;
1512     LogStream ls(lt);
1513     phase_timings()->print_cycle_on(&ls);
1514     if (ShenandoahEvacTracking) {
1515       ShenandoahCycleStats  evac_stats = evac_tracker()->flush_cycle_to_global();
1516       evac_tracker()->print_evacuations_on(&ls, &evac_stats.workers,
1517                                                &evac_stats.mutators);
1518     }
1519   }
1520 
1521   // Commit statistics to globals
1522   phase_timings()->flush_cycle_to_global();
1523 }
1524 
1525 size_t ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) const {
1526   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1527   assert(!start->has_live(), "liveness must be zero");
1528 
1529   // Do not try to get the size of this humongous object. STW collections will
1530   // have already unloaded classes, so an unmarked object may have a bad klass pointer.
1531   ShenandoahHeapRegion* region = start;
1532   size_t index = region->index();
1533   do {
1534     assert(region->is_humongous(), "Expect correct humongous start or continuation");
1535     assert(!region->is_cset(), "Humongous region should not be in collection set");
1536     region->make_trash_immediate();
1537     region = get_region(++index);
1538   } while (region != nullptr && region->is_humongous_continuation());
1539 
1540   // Return number of regions trashed
1541   return index - start->index();
1542 }
1543 
1544 class ShenandoahCheckCleanGCLABClosure : public ThreadClosure {
1545 public:
1546   ShenandoahCheckCleanGCLABClosure() {}
1547   void do_thread(Thread* thread) {
1548     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1549     assert(gclab != nullptr, "GCLAB should be initialized for %s", thread->name());
1550     assert(gclab->words_remaining() == 0, "GCLAB should not need retirement");
1551 
1552     if (ShenandoahHeap::heap()->mode()->is_generational()) {
1553       ShenandoahPLAB* shenandoah_plab = ShenandoahThreadLocalData::shenandoah_plab(thread);
1554       assert(shenandoah_plab != nullptr, "PLAB should be initialized for %s", thread->name());
1555       assert(shenandoah_plab->plab()->words_remaining() == 0, "PLAB should not need retirement");
1556     }
1557   }
1558 };
1559 
1560 void ShenandoahHeap::labs_make_parsable() {
1561   assert(UseTLAB, "Only call with UseTLAB");
1562 
1563   ShenandoahRetireGCLABClosure cl(false);
1564 
1565   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1566     ThreadLocalAllocBuffer& tlab = t->tlab();
1567     tlab.make_parsable();
1568     if (ZeroTLAB) {
1569       t->retire_tlab();
1570     }
1571     cl.do_thread(t);
1572   }
1573 
1574   workers()->threads_do(&cl);
1575 
1576   if (safepoint_workers() != nullptr) {
1577     safepoint_workers()->threads_do(&cl);
1578   }
1579 }
1580 
1581 void ShenandoahHeap::tlabs_retire(bool resize) {
1582   assert(UseTLAB, "Only call with UseTLAB");
1583   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1584 
1585   ThreadLocalAllocStats stats;
1586 
1587   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1588     t->retire_tlab(&stats);
1589     if (resize) {
1590       t->tlab().resize();
1591     }
1592   }
1593 
1594   stats.publish();
1595 
1596 #ifdef ASSERT
1597   ShenandoahCheckCleanGCLABClosure cl;
1598   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1599     cl.do_thread(t);
1600   }
1601   workers()->threads_do(&cl);
1602 #endif
1603 }
1604 
1605 void ShenandoahHeap::gclabs_retire(bool resize) {
1606   assert(UseTLAB, "Only call with UseTLAB");
1607   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1608 
1609   ShenandoahRetireGCLABClosure cl(resize);
1610   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1611     cl.do_thread(t);
1612   }
1613 
1614   workers()->threads_do(&cl);
1615 
1616   if (safepoint_workers() != nullptr) {
1617     safepoint_workers()->threads_do(&cl);
1618   }
1619 }
1620 
1621 // Returns size in bytes
1622 size_t ShenandoahHeap::unsafe_max_tlab_alloc() const {
1623   // Return the max allowed size, and let the allocation path
1624   // figure out the safe size for current allocation.
1625   return ShenandoahHeapRegion::max_tlab_size_bytes();
1626 }
1627 
1628 size_t ShenandoahHeap::max_tlab_size() const {
1629   // Returns size in words
1630   return ShenandoahHeapRegion::max_tlab_size_words();
1631 }
1632 
1633 void ShenandoahHeap::collect_as_vm_thread(GCCause::Cause cause) {
1634   // These requests are ignored because we can't easily have Shenandoah jump into
1635   // a synchronous (degenerated or full) cycle while it is in the middle of a concurrent
1636   // cycle. We _could_ cancel the concurrent cycle and then try to run a cycle directly
1637   // on the VM thread, but this would confuse the control thread mightily and doesn't
1638   // seem worth the trouble. Instead, we will have the caller thread run (and wait for) a
1639   // concurrent cycle in the prologue of the heap inspect/dump operation (see VM_HeapDumper::doit_prologue).
1640   // This is how other concurrent collectors in the JVM handle this scenario as well.
1641   assert(Thread::current()->is_VM_thread(), "Should be the VM thread");
1642   guarantee(cause == GCCause::_heap_dump || cause == GCCause::_heap_inspection, "Invalid cause");
1643 }
1644 
1645 void ShenandoahHeap::collect(GCCause::Cause cause) {
1646   control_thread()->request_gc(cause);
1647 }
1648 
1649 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1650   // This method is only called by `CollectedHeap::collect_as_vm_thread`, which we have
1651   // overridden to do nothing. See the comment there for an explanation of how heap inspections
1652   // work for Shenandoah.
1653   ShouldNotReachHere();
1654 }
1655 
1656 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1657   ShenandoahHeapRegion* r = heap_region_containing(addr);
1658   if (r != nullptr) {
1659     return r->block_start(addr);
1660   }
1661   return nullptr;
1662 }
1663 
1664 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1665   ShenandoahHeapRegion* r = heap_region_containing(addr);
1666   return r->block_is_obj(addr);
1667 }
1668 
1669 bool ShenandoahHeap::print_location(outputStream* st, void* addr) const {
1670   return BlockLocationPrinter<ShenandoahHeap>::print_location(st, addr);
1671 }
1672 
1673 void ShenandoahHeap::prepare_for_verify() {
1674   if (SafepointSynchronize::is_at_safepoint() && UseTLAB) {
1675     labs_make_parsable();
1676   }
1677 }
1678 
1679 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1680   if (_shenandoah_policy->is_at_shutdown()) {
1681     return;
1682   }
1683 
1684   if (_control_thread != nullptr) {
1685     tcl->do_thread(_control_thread);
1686   }
1687 
1688   if (_uncommit_thread != nullptr) {
1689     tcl->do_thread(_uncommit_thread);
1690   }
1691 
1692   workers()->threads_do(tcl);
1693   if (_safepoint_workers != nullptr) {
1694     _safepoint_workers->threads_do(tcl);
1695   }
1696 }
1697 
1698 void ShenandoahHeap::print_tracing_info() const {
1699   LogTarget(Info, gc, stats) lt;
1700   if (lt.is_enabled()) {
1701     ResourceMark rm;
1702     LogStream ls(lt);
1703 
1704     if (ShenandoahEvacTracking) {
1705       evac_tracker()->print_global_on(&ls);
1706       ls.cr();
1707       ls.cr();
1708     }
1709 
1710     phase_timings()->print_global_on(&ls);
1711 
1712     ls.cr();
1713     ls.cr();
1714 
1715     shenandoah_policy()->print_gc_stats(&ls);
1716 
1717     ls.cr();
1718     ls.cr();
1719   }
1720 }
1721 
1722 // Active generation may only be set by the VM thread at a safepoint.
1723 void ShenandoahHeap::set_active_generation(ShenandoahGeneration* generation) {
1724   assert(Thread::current()->is_VM_thread(), "Only the VM Thread");
1725   assert(SafepointSynchronize::is_at_safepoint(), "Only at a safepoint!");
1726   _active_generation = generation;
1727 }
1728 
1729 void ShenandoahHeap::on_cycle_start(GCCause::Cause cause, ShenandoahGeneration* generation,
1730                                     bool is_degenerated, bool is_out_of_cycle) {
1731   shenandoah_policy()->record_collection_cause(cause);
1732 
1733   const GCCause::Cause current = gc_cause();
1734   assert(current == GCCause::_no_gc, "Over-writing cause: %s, with: %s",
1735          GCCause::to_string(current), GCCause::to_string(cause));
1736 
1737   set_gc_cause(cause);
1738 
1739   if (is_degenerated) {
1740     generation->heuristics()->record_degenerated_cycle_start(is_out_of_cycle);
1741   } else {
1742     generation->heuristics()->record_cycle_start();
1743   }
1744 }
1745 
1746 void ShenandoahHeap::on_cycle_end(ShenandoahGeneration* generation) {
1747   assert(gc_cause() != GCCause::_no_gc, "cause wasn't set");
1748 
1749   generation->heuristics()->record_cycle_end();
1750   if (mode()->is_generational() && generation->is_global()) {
1751     // If we just completed a GLOBAL GC, claim credit for completion of young-gen and old-gen GC as well
1752     young_generation()->heuristics()->record_cycle_end();
1753     old_generation()->heuristics()->record_cycle_end();
1754   }
1755 
1756   set_gc_cause(GCCause::_no_gc);
1757 }
1758 
1759 void ShenandoahHeap::verify(VerifyOption vo) {
1760   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1761     if (ShenandoahVerify) {
1762       verifier()->verify_generic(active_generation(), vo);
1763     } else {
1764       // TODO: Consider allocating verification bitmaps on demand,
1765       // and turn this on unconditionally.
1766     }
1767   }
1768 }
1769 size_t ShenandoahHeap::tlab_capacity() const {
1770   return _free_set->capacity_not_holding_lock();
1771 }
1772 
1773 class ObjectIterateScanRootClosure : public BasicOopIterateClosure {
1774 private:
1775   MarkBitMap* _bitmap;
1776   ShenandoahScanObjectStack* _oop_stack;
1777   ShenandoahHeap* const _heap;
1778   ShenandoahMarkingContext* const _marking_context;
1779 
1780   template <class T>
1781   void do_oop_work(T* p) {
1782     T o = RawAccess<>::oop_load(p);
1783     if (!CompressedOops::is_null(o)) {
1784       oop obj = CompressedOops::decode_not_null(o);
1785       if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1786         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1787         return;
1788       }
1789       obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj);
1790 
1791       assert(oopDesc::is_oop(obj), "must be a valid oop");
1792       if (!_bitmap->is_marked(obj)) {
1793         _bitmap->mark(obj);
1794         _oop_stack->push(obj);
1795       }
1796     }
1797   }
1798 public:
1799   ObjectIterateScanRootClosure(MarkBitMap* bitmap, ShenandoahScanObjectStack* oop_stack) :
1800     _bitmap(bitmap), _oop_stack(oop_stack), _heap(ShenandoahHeap::heap()),
1801     _marking_context(_heap->marking_context()) {}
1802   void do_oop(oop* p)       { do_oop_work(p); }
1803   void do_oop(narrowOop* p) { do_oop_work(p); }
1804 };
1805 
1806 /*
1807  * This is public API, used in preparation of object_iterate().
1808  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1809  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1810  * control, we call SH::tlabs_retire, SH::gclabs_retire.
1811  */
1812 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1813   // No-op.
1814 }
1815 
1816 /*
1817  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1818  *
1819  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1820  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1821  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1822  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1823  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1824  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1825  * wiped the bitmap in preparation for next marking).
1826  *
1827  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1828  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1829  * is allowed to report dead objects, but is not required to do so.
1830  */
1831 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1832   // Reset bitmap
1833   if (!prepare_aux_bitmap_for_iteration())
1834     return;
1835 
1836   ShenandoahScanObjectStack oop_stack;
1837   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1838   // Seed the stack with root scan
1839   scan_roots_for_iteration(&oop_stack, &oops);
1840 
1841   // Work through the oop stack to traverse heap
1842   while (! oop_stack.is_empty()) {
1843     oop obj = oop_stack.pop();
1844     assert(oopDesc::is_oop(obj), "must be a valid oop");
1845     cl->do_object(obj);
1846     obj->oop_iterate(&oops);
1847   }
1848 
1849   assert(oop_stack.is_empty(), "should be empty");
1850   // Reclaim bitmap
1851   reclaim_aux_bitmap_for_iteration();
1852 }
1853 
1854 bool ShenandoahHeap::prepare_aux_bitmap_for_iteration() {
1855   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1856   if (!_aux_bitmap_region_special) {
1857     bool success = os::commit_memory((char *) _aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false);
1858     if (!success) {
1859       log_warning(gc)("Auxiliary marking bitmap commit failed: " PTR_FORMAT " (%zu bytes)",
1860                       p2i(_aux_bitmap_region.start()), _aux_bitmap_region.byte_size());
1861       return false;
1862     }
1863   }
1864   _aux_bit_map.clear();
1865   return true;
1866 }
1867 
1868 void ShenandoahHeap::scan_roots_for_iteration(ShenandoahScanObjectStack* oop_stack, ObjectIterateScanRootClosure* oops) {
1869   // Process GC roots according to current GC cycle
1870   // This populates the work stack with initial objects
1871   // It is important to relinquish the associated locks before diving
1872   // into heap dumper
1873   uint n_workers = safepoint_workers() != nullptr ? safepoint_workers()->active_workers() : 1;
1874   ShenandoahHeapIterationRootScanner rp(n_workers);
1875   rp.roots_do(oops);
1876 }
1877 
1878 void ShenandoahHeap::reclaim_aux_bitmap_for_iteration() {
1879   if (!_aux_bitmap_region_special) {
1880     os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size());
1881   }
1882 }
1883 
1884 // Closure for parallelly iterate objects
1885 class ShenandoahObjectIterateParScanClosure : public BasicOopIterateClosure {
1886 private:
1887   MarkBitMap* _bitmap;
1888   ShenandoahObjToScanQueue* _queue;
1889   ShenandoahHeap* const _heap;
1890   ShenandoahMarkingContext* const _marking_context;
1891 
1892   template <class T>
1893   void do_oop_work(T* p) {
1894     T o = RawAccess<>::oop_load(p);
1895     if (!CompressedOops::is_null(o)) {
1896       oop obj = CompressedOops::decode_not_null(o);
1897       if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1898         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1899         return;
1900       }
1901       obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj);
1902 
1903       assert(oopDesc::is_oop(obj), "Must be a valid oop");
1904       if (_bitmap->par_mark(obj)) {
1905         _queue->push(ShenandoahMarkTask(obj));
1906       }
1907     }
1908   }
1909 public:
1910   ShenandoahObjectIterateParScanClosure(MarkBitMap* bitmap, ShenandoahObjToScanQueue* q) :
1911     _bitmap(bitmap), _queue(q), _heap(ShenandoahHeap::heap()),
1912     _marking_context(_heap->marking_context()) {}
1913   void do_oop(oop* p)       { do_oop_work(p); }
1914   void do_oop(narrowOop* p) { do_oop_work(p); }
1915 };
1916 
1917 // Object iterator for parallel heap iteraion.
1918 // The root scanning phase happenes in construction as a preparation of
1919 // parallel marking queues.
1920 // Every worker processes it's own marking queue. work-stealing is used
1921 // to balance workload.
1922 class ShenandoahParallelObjectIterator : public ParallelObjectIteratorImpl {
1923 private:
1924   uint                         _num_workers;
1925   bool                         _init_ready;
1926   MarkBitMap*                  _aux_bit_map;
1927   ShenandoahHeap*              _heap;
1928   ShenandoahScanObjectStack    _roots_stack; // global roots stack
1929   ShenandoahObjToScanQueueSet* _task_queues;
1930 public:
1931   ShenandoahParallelObjectIterator(uint num_workers, MarkBitMap* bitmap) :
1932         _num_workers(num_workers),
1933         _init_ready(false),
1934         _aux_bit_map(bitmap),
1935         _heap(ShenandoahHeap::heap()) {
1936     // Initialize bitmap
1937     _init_ready = _heap->prepare_aux_bitmap_for_iteration();
1938     if (!_init_ready) {
1939       return;
1940     }
1941 
1942     ObjectIterateScanRootClosure oops(_aux_bit_map, &_roots_stack);
1943     _heap->scan_roots_for_iteration(&_roots_stack, &oops);
1944 
1945     _init_ready = prepare_worker_queues();
1946   }
1947 
1948   ~ShenandoahParallelObjectIterator() {
1949     // Reclaim bitmap
1950     _heap->reclaim_aux_bitmap_for_iteration();
1951     // Reclaim queue for workers
1952     if (_task_queues!= nullptr) {
1953       for (uint i = 0; i < _num_workers; ++i) {
1954         ShenandoahObjToScanQueue* q = _task_queues->queue(i);
1955         if (q != nullptr) {
1956           delete q;
1957           _task_queues->register_queue(i, nullptr);
1958         }
1959       }
1960       delete _task_queues;
1961       _task_queues = nullptr;
1962     }
1963   }
1964 
1965   virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
1966     if (_init_ready) {
1967       object_iterate_parallel(cl, worker_id, _task_queues);
1968     }
1969   }
1970 
1971 private:
1972   // Divide global root_stack into worker queues
1973   bool prepare_worker_queues() {
1974     _task_queues = new ShenandoahObjToScanQueueSet((int) _num_workers);
1975     // Initialize queues for every workers
1976     for (uint i = 0; i < _num_workers; ++i) {
1977       ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue();
1978       _task_queues->register_queue(i, task_queue);
1979     }
1980     // Divide roots among the workers. Assume that object referencing distribution
1981     // is related with root kind, use round-robin to make every worker have same chance
1982     // to process every kind of roots
1983     size_t roots_num = _roots_stack.size();
1984     if (roots_num == 0) {
1985       // No work to do
1986       return false;
1987     }
1988 
1989     for (uint j = 0; j < roots_num; j++) {
1990       uint stack_id = j % _num_workers;
1991       oop obj = _roots_stack.pop();
1992       _task_queues->queue(stack_id)->push(ShenandoahMarkTask(obj));
1993     }
1994     return true;
1995   }
1996 
1997   void object_iterate_parallel(ObjectClosure* cl,
1998                                uint worker_id,
1999                                ShenandoahObjToScanQueueSet* queue_set) {
2000     assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
2001     assert(queue_set != nullptr, "task queue must not be null");
2002 
2003     ShenandoahObjToScanQueue* q = queue_set->queue(worker_id);
2004     assert(q != nullptr, "object iterate queue must not be null");
2005 
2006     ShenandoahMarkTask t;
2007     ShenandoahObjectIterateParScanClosure oops(_aux_bit_map, q);
2008 
2009     // Work through the queue to traverse heap.
2010     // Steal when there is no task in queue.
2011     while (q->pop(t) || queue_set->steal(worker_id, t)) {
2012       oop obj = t.obj();
2013       assert(oopDesc::is_oop(obj), "must be a valid oop");
2014       cl->do_object(obj);
2015       obj->oop_iterate(&oops);
2016     }
2017     assert(q->is_empty(), "should be empty");
2018   }
2019 };
2020 
2021 ParallelObjectIteratorImpl* ShenandoahHeap::parallel_object_iterator(uint workers) {
2022   return new ShenandoahParallelObjectIterator(workers, &_aux_bit_map);
2023 }
2024 
2025 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
2026 void ShenandoahHeap::keep_alive(oop obj) {
2027   if (is_concurrent_mark_in_progress() && (obj != nullptr)) {
2028     ShenandoahBarrierSet::barrier_set()->enqueue(obj);
2029   }
2030 }
2031 
2032 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
2033   for (size_t i = 0; i < num_regions(); i++) {
2034     ShenandoahHeapRegion* current = get_region(i);
2035     blk->heap_region_do(current);
2036   }
2037 }
2038 
2039 class ShenandoahHeapRegionIteratorTask : public WorkerTask {
2040 private:
2041   ShenandoahRegionIterator _regions;
2042   ShenandoahHeapRegionClosure* _closure;
2043 
2044 public:
2045   ShenandoahHeapRegionIteratorTask(ShenandoahHeapRegionClosure* closure)
2046     : WorkerTask("Shenandoah Heap Region Iterator")
2047     , _closure(closure) {}
2048 
2049   void work(uint worker_id) override {
2050     ShenandoahParallelWorkerSession worker_session(worker_id);
2051     ShenandoahHeapRegion* region = _regions.next();
2052     while (region != nullptr) {
2053       _closure->heap_region_do(region);
2054       region = _regions.next();
2055     }
2056   }
2057 };
2058 
2059 class ShenandoahParallelHeapRegionTask : public WorkerTask {
2060 private:
2061   ShenandoahHeap* const _heap;
2062   ShenandoahHeapRegionClosure* const _blk;
2063   size_t const _stride;
2064 
2065   shenandoah_padding(0);
2066   Atomic<size_t> _index;
2067   shenandoah_padding(1);
2068 
2069 public:
2070   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk, size_t stride) :
2071           WorkerTask("Shenandoah Parallel Region Operation"),
2072           _heap(ShenandoahHeap::heap()), _blk(blk), _stride(stride), _index(0) {}
2073 
2074   void work(uint worker_id) {
2075     ShenandoahParallelWorkerSession worker_session(worker_id);
2076     size_t stride = _stride;
2077 
2078     size_t max = _heap->num_regions();
2079     while (_index.load_relaxed() < max) {
2080       size_t cur = _index.fetch_then_add(stride, memory_order_relaxed);
2081       size_t start = cur;
2082       size_t end = MIN2(cur + stride, max);
2083       if (start >= max) break;
2084 
2085       for (size_t i = cur; i < end; i++) {
2086         ShenandoahHeapRegion* current = _heap->get_region(i);
2087         _blk->heap_region_do(current);
2088       }
2089     }
2090   }
2091 };
2092 
2093 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
2094   assert(blk->is_thread_safe(), "Only thread-safe closures here");
2095   const uint active_workers = workers()->active_workers();
2096   const size_t n_regions = num_regions();
2097   size_t stride = blk->parallel_region_stride();
2098   if (stride == 0 && active_workers > 1) {
2099     // Automatically derive the stride to balance the work between threads
2100     // evenly. Do not try to split work if below the reasonable threshold.
2101     constexpr size_t threshold = 4096;
2102     stride = n_regions <= threshold ?
2103             threshold :
2104             (n_regions + active_workers - 1) / active_workers;
2105   }
2106 
2107   if (n_regions > stride && active_workers > 1) {
2108     ShenandoahParallelHeapRegionTask task(blk, stride);
2109     workers()->run_task(&task);
2110   } else {
2111     heap_region_iterate(blk);
2112   }
2113 }
2114 
2115 void ShenandoahHeap::heap_region_iterator(ShenandoahHeapRegionClosure* closure) const {
2116   ShenandoahHeapRegionIteratorTask task(closure);
2117   workers()->run_task(&task);
2118 }
2119 
2120 class ShenandoahRendezvousHandshakeClosure : public HandshakeClosure {
2121 public:
2122   inline ShenandoahRendezvousHandshakeClosure(const char* name) : HandshakeClosure(name) {}
2123   inline void do_thread(Thread* thread) {}
2124 };
2125 
2126 void ShenandoahHeap::rendezvous_threads(const char* name) {
2127   ShenandoahRendezvousHandshakeClosure cl(name);
2128   Handshake::execute(&cl);
2129 }
2130 
2131 void ShenandoahHeap::recycle_trash() {
2132   free_set()->recycle_trash();
2133 }
2134 
2135 void ShenandoahHeap::do_class_unloading() {
2136   _unloader.unload();
2137   if (mode()->is_generational()) {
2138     old_generation()->set_parsable(false);
2139   }
2140 }
2141 
2142 void ShenandoahHeap::stw_weak_refs(ShenandoahGeneration* generation, bool full_gc) {
2143   // Weak refs processing
2144   ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs
2145                                                 : ShenandoahPhaseTimings::degen_gc_weakrefs;
2146   ShenandoahTimingsTracker t(phase);
2147   ShenandoahGCWorkerPhase worker_phase(phase);
2148   generation->ref_processor()->process_references(phase, workers(), false /* concurrent */);
2149 }
2150 
2151 void ShenandoahHeap::prepare_update_heap_references() {
2152   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2153 
2154   // Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to
2155   // make them parsable for update code to work correctly. Plus, we can compute new sizes
2156   // for future GCLABs here.
2157   if (UseTLAB) {
2158     ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs);
2159     gclabs_retire(ResizeTLAB);
2160   }
2161 
2162   _update_refs_iterator.reset();
2163 }
2164 
2165 void ShenandoahHeap::propagate_gc_state_to_all_threads() {
2166   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at Shenandoah safepoint");
2167   if (_gc_state_changed) {
2168     // If we are only marking old, we do not need to process young pointers
2169     ShenandoahBarrierSet::satb_mark_queue_set().set_filter_out_young(
2170       is_concurrent_old_mark_in_progress() && !is_concurrent_young_mark_in_progress()
2171     );
2172     ShenandoahGCStatePropagatorHandshakeClosure propagator(_gc_state.raw_value());
2173     Threads::threads_do(&propagator);
2174     _gc_state_changed = false;
2175   }
2176 }
2177 
2178 void ShenandoahHeap::set_gc_state_at_safepoint(uint mask, bool value) {
2179   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at Shenandoah safepoint");
2180   _gc_state.set_cond(mask, value);
2181   _gc_state_changed = true;
2182 }
2183 
2184 void ShenandoahHeap::set_gc_state_concurrent(uint mask, bool value) {
2185   // Holding the thread lock here assures that any thread created after we change the gc
2186   // state will have the correct state. It also prevents attaching threads from seeing
2187   // an inconsistent state. See ShenandoahBarrierSet::on_thread_attach for reference. Established
2188   // threads will use their thread local copy of the gc state (changed by a handshake, or on a
2189   // safepoint).
2190   assert(Threads_lock->is_locked(), "Must hold thread lock for concurrent gc state change");
2191   _gc_state.set_cond(mask, value);
2192 }
2193 
2194 void ShenandoahHeap::set_concurrent_young_mark_in_progress(bool in_progress) {
2195   uint mask;
2196   assert(!has_forwarded_objects(), "Young marking is not concurrent with evacuation");
2197   if (!in_progress && is_concurrent_old_mark_in_progress()) {
2198     assert(mode()->is_generational(), "Only generational GC has old marking");
2199     assert(_gc_state.is_set(MARKING), "concurrent_old_marking_in_progress implies MARKING");
2200     // If old-marking is in progress when we turn off YOUNG_MARKING, leave MARKING (and OLD_MARKING) on
2201     mask = YOUNG_MARKING;
2202   } else {
2203     mask = MARKING | YOUNG_MARKING;
2204   }
2205   set_gc_state_at_safepoint(mask, in_progress);
2206   manage_satb_barrier(in_progress);
2207 }
2208 
2209 void ShenandoahHeap::set_concurrent_old_mark_in_progress(bool in_progress) {
2210 #ifdef ASSERT
2211   // has_forwarded_objects() iff UPDATE_REFS or EVACUATION
2212   bool has_forwarded = has_forwarded_objects();
2213   bool updating_or_evacuating = _gc_state.is_set(UPDATE_REFS | EVACUATION);
2214   bool evacuating = _gc_state.is_set(EVACUATION);
2215   assert ((has_forwarded == updating_or_evacuating) || (evacuating && !has_forwarded && collection_set()->is_empty()),
2216           "Updating or evacuating iff has forwarded objects, or if evacuation phase is promoting in place without forwarding");
2217 #endif
2218   if (!in_progress && is_concurrent_young_mark_in_progress()) {
2219     // If young-marking is in progress when we turn off OLD_MARKING, leave MARKING (and YOUNG_MARKING) on
2220     assert(_gc_state.is_set(MARKING), "concurrent_young_marking_in_progress implies MARKING");
2221     set_gc_state_at_safepoint(OLD_MARKING, in_progress);
2222   } else {
2223     set_gc_state_at_safepoint(MARKING | OLD_MARKING, in_progress);
2224   }
2225   manage_satb_barrier(in_progress);
2226 }
2227 
2228 bool ShenandoahHeap::is_prepare_for_old_mark_in_progress() const {
2229   return old_generation()->is_preparing_for_mark();
2230 }
2231 
2232 void ShenandoahHeap::manage_satb_barrier(bool active) {
2233   if (is_concurrent_mark_in_progress()) {
2234     // Ignore request to deactivate barrier while concurrent mark is in progress.
2235     // Do not attempt to re-activate the barrier if it is already active.
2236     if (active && !ShenandoahBarrierSet::satb_mark_queue_set().is_active()) {
2237       ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active);
2238     }
2239   } else {
2240     // No concurrent marking is in progress so honor request to deactivate,
2241     // but only if the barrier is already active.
2242     if (!active && ShenandoahBarrierSet::satb_mark_queue_set().is_active()) {
2243       ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active);
2244     }
2245   }
2246 }
2247 
2248 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
2249   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
2250   set_gc_state_at_safepoint(EVACUATION, in_progress);
2251 }
2252 
2253 void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) {
2254   if (in_progress) {
2255     _concurrent_strong_root_in_progress.set();
2256   } else {
2257     _concurrent_strong_root_in_progress.unset();
2258   }
2259 }
2260 
2261 void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) {
2262   set_gc_state_at_safepoint(WEAK_ROOTS, cond);
2263 }
2264 
2265 GCTracer* ShenandoahHeap::tracer() {
2266   return shenandoah_policy()->tracer();
2267 }
2268 
2269 size_t ShenandoahHeap::tlab_used() const {
2270   return _free_set->used_not_holding_lock();
2271 }
2272 
2273 bool ShenandoahHeap::try_cancel_gc(GCCause::Cause cause) {
2274   while (true) {
2275     const GCCause::Cause prev = _cancelled_gc.get();
2276     if (prev != GCCause::_no_gc && prev != GCCause::_shenandoah_concurrent_gc && cause != GCCause::_shenandoah_stop_vm) {
2277       // Only when the gc has not been cancelled, or it has been cancelled to interrupt an old marking cycle
2278       // do we allow the new cancellation request to happen. We make an exception for stopping the VM.
2279       return false;
2280     }
2281 
2282     if (_cancelled_gc.cmpxchg(cause, prev) == prev) {
2283       return true;
2284     }
2285   }
2286 }
2287 
2288 void ShenandoahHeap::cancel_concurrent_mark() {
2289   if (mode()->is_generational()) {
2290     young_generation()->cancel_marking();
2291     old_generation()->cancel_marking();
2292   }
2293 
2294   global_generation()->cancel_marking();
2295 
2296   ShenandoahBarrierSet::satb_mark_queue_set().abandon_partial_marking();
2297 }
2298 
2299 bool ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
2300   if (try_cancel_gc(cause)) {
2301     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
2302     log_info(gc,thread)("%s", msg.buffer());
2303     Events::log(Thread::current(), "%s", msg.buffer());
2304     _cancel_requested_time = os::elapsedTime();
2305     return true;
2306   }
2307   return false;
2308 }
2309 
2310 uint ShenandoahHeap::max_workers() {
2311   return _max_workers;
2312 }
2313 
2314 void ShenandoahHeap::stop() {
2315   // The shutdown sequence should be able to terminate when GC is running.
2316 
2317   // Step 0. Notify policy to disable event recording and prevent visiting gc threads during shutdown
2318   _shenandoah_policy->record_shutdown();
2319 
2320   // Step 1. Stop reporting on gc thread cpu utilization
2321   mmu_tracker()->stop();
2322 
2323   // Step 2. Stop decaying allocation rate.
2324   _alloc_rate_decay.disenroll();
2325 
2326   // Step 3. Wait until GC worker exits normally (this will cancel any ongoing GC).
2327   control_thread()->stop();
2328 
2329   // Step 4. Shutdown uncommit thread.
2330   if (_uncommit_thread != nullptr) {
2331     _uncommit_thread->stop();
2332   }
2333 }
2334 
2335 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
2336   if (!unload_classes()) return;
2337   ClassUnloadingContext ctx(_workers->active_workers(),
2338                             true /* unregister_nmethods_during_purge */,
2339                             false /* lock_nmethod_free_separately */);
2340 
2341   // Unload classes and purge SystemDictionary.
2342   {
2343     ShenandoahPhaseTimings::Phase phase = full_gc ?
2344                                           ShenandoahPhaseTimings::full_gc_purge_class_unload :
2345                                           ShenandoahPhaseTimings::degen_gc_purge_class_unload;
2346     ShenandoahIsAliveSelector is_alive;
2347     {
2348       CodeCache::UnlinkingScope scope(is_alive.is_alive_closure());
2349       ShenandoahGCPhase gc_phase(phase);
2350       ShenandoahGCWorkerPhase worker_phase(phase);
2351       bool unloading_occurred = SystemDictionary::do_unloading(gc_timer());
2352 
2353       ShenandoahClassUnloadingTask unlink_task(phase, unloading_occurred);
2354       _workers->run_task(&unlink_task);
2355     }
2356     // Release unloaded nmethods's memory.
2357     ClassUnloadingContext::context()->purge_and_free_nmethods();
2358   }
2359 
2360   {
2361     ShenandoahGCPhase phase(full_gc ?
2362                             ShenandoahPhaseTimings::full_gc_purge_cldg :
2363                             ShenandoahPhaseTimings::degen_gc_purge_cldg);
2364     ClassLoaderDataGraph::purge(true /* at_safepoint */);
2365   }
2366   // Resize and verify metaspace
2367   MetaspaceGC::compute_new_size();
2368 
2369   if (mode()->is_generational()) {
2370     old_generation()->set_parsable(false);
2371   }
2372 
2373   DEBUG_ONLY(MetaspaceUtils::verify();)
2374 }
2375 
2376 // Weak roots are either pre-evacuated (final mark) or updated (final update refs),
2377 // so they should not have forwarded oops.
2378 // However, we do need to "null" dead oops in the roots, if can not be done
2379 // in concurrent cycles.
2380 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
2381   uint num_workers = _workers->active_workers();
2382   ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
2383                                                ShenandoahPhaseTimings::full_gc_purge_weak_par :
2384                                                ShenandoahPhaseTimings::degen_gc_purge_weak_par;
2385   ShenandoahGCPhase phase(timing_phase);
2386   ShenandoahGCWorkerPhase worker_phase(timing_phase);
2387   // Cleanup weak roots
2388   if (has_forwarded_objects()) {
2389     ShenandoahForwardedIsAliveClosure is_alive;
2390     ShenandoahNonConcUpdateRefsClosure keep_alive;
2391     ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahNonConcUpdateRefsClosure>
2392       cleaning_task(timing_phase, &is_alive, &keep_alive, num_workers);
2393     _workers->run_task(&cleaning_task);
2394   } else {
2395     ShenandoahIsAliveClosure is_alive;
2396 #ifdef ASSERT
2397     ShenandoahAssertNotForwardedClosure verify_cl;
2398     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
2399       cleaning_task(timing_phase, &is_alive, &verify_cl, num_workers);
2400 #else
2401     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
2402       cleaning_task(timing_phase, &is_alive, &do_nothing_cl, num_workers);
2403 #endif
2404     _workers->run_task(&cleaning_task);
2405   }
2406 }
2407 
2408 void ShenandoahHeap::parallel_cleaning(ShenandoahGeneration* generation, bool full_gc) {
2409   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2410   assert(is_stw_gc_in_progress(), "Only for Degenerated and Full GC");
2411   ShenandoahGCPhase phase(full_gc ?
2412                           ShenandoahPhaseTimings::full_gc_purge :
2413                           ShenandoahPhaseTimings::degen_gc_purge);
2414   stw_weak_refs(generation, full_gc);
2415   stw_process_weak_roots(full_gc);
2416   stw_unload_classes(full_gc);
2417 }
2418 
2419 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
2420   set_gc_state_at_safepoint(HAS_FORWARDED, cond);
2421 }
2422 
2423 void ShenandoahHeap::set_unload_classes(bool uc) {
2424   _unload_classes.set_cond(uc);
2425 }
2426 
2427 bool ShenandoahHeap::unload_classes() const {
2428   return _unload_classes.is_set();
2429 }
2430 
2431 address ShenandoahHeap::in_cset_fast_test_addr() {
2432   ShenandoahHeap* heap = ShenandoahHeap::heap();
2433   assert(heap->collection_set() != nullptr, "Sanity");
2434   return (address) heap->collection_set()->biased_map_address();
2435 }
2436 
2437 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2438   _degenerated_gc_in_progress.set_cond(in_progress);
2439 }
2440 
2441 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2442   _full_gc_in_progress.set_cond(in_progress);
2443 }
2444 
2445 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2446   assert (is_full_gc_in_progress(), "should be");
2447   _full_gc_move_in_progress.set_cond(in_progress);
2448 }
2449 
2450 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2451   set_gc_state_at_safepoint(UPDATE_REFS, in_progress);
2452 }
2453 
2454 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2455   ShenandoahCodeRoots::register_nmethod(nm);
2456 }
2457 
2458 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2459   ShenandoahCodeRoots::unregister_nmethod(nm);
2460 }
2461 
2462 void ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2463   assert(thr == JavaThread::current(), "Sanity");
2464   size_t reg_idx_pin = heap_region_index_containing(o);
2465   size_t reg_idx_cached = ShenandoahThreadLocalData::pin_cache_region(thr);
2466   size_t count = ShenandoahThreadLocalData::pin_cache_count(thr);
2467   if (reg_idx_pin == reg_idx_cached) {
2468     ShenandoahThreadLocalData::pin_cache_set_count(thr, count + 1);
2469   } else {
2470     if (count != 0) {
2471       get_region(reg_idx_cached)->record_pin(count);
2472     }
2473     ShenandoahThreadLocalData::pin_cache_set_region(thr, reg_idx_pin);
2474     ShenandoahThreadLocalData::pin_cache_set_count(thr, 1);
2475   }
2476 }
2477 
2478 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2479   assert(thr == JavaThread::current(), "Sanity");
2480   size_t reg_idx_pin = heap_region_index_containing(o);
2481   size_t reg_idx_cached = ShenandoahThreadLocalData::pin_cache_region(thr);
2482   if (reg_idx_pin == reg_idx_cached) {
2483     size_t count = ShenandoahThreadLocalData::pin_cache_count(thr);
2484     ShenandoahThreadLocalData::pin_cache_set_count(thr, count - 1);
2485   } else {
2486     get_region(reg_idx_pin)->record_unpin();
2487   }
2488 }
2489 
2490 void ShenandoahHeap::flush_region_pin_cache(JavaThread* thr) {
2491   size_t count = ShenandoahThreadLocalData::pin_cache_count(thr);
2492   if (count != 0) {
2493     size_t reg_idx_cached = ShenandoahThreadLocalData::pin_cache_region(thr);
2494     get_region(reg_idx_cached)->record_pin(count);
2495     ShenandoahThreadLocalData::pin_cache_set_count(thr, 0);
2496   }
2497 }
2498 
2499 void ShenandoahHeap::flush_region_pin_cache() {
2500   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2501   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
2502     flush_region_pin_cache(t);
2503   }
2504 }
2505 
2506 void ShenandoahHeap::sync_pinned_region_status() {
2507   flush_region_pin_cache();
2508   ShenandoahHeapLocker locker(lock());
2509 
2510   for (size_t i = 0; i < num_regions(); i++) {
2511     ShenandoahHeapRegion *r = get_region(i);
2512     if (r->is_active()) {
2513       if (r->is_pinned()) {
2514         if (r->pin_count() == 0) {
2515           r->make_unpinned();
2516         }
2517       } else {
2518         if (r->pin_count() > 0) {
2519           r->make_pinned();
2520         }
2521       }
2522     }
2523   }
2524 
2525   assert_pinned_region_status();
2526 }
2527 
2528 #ifdef ASSERT
2529 void ShenandoahHeap::assert_pinned_region_status() const {
2530   assert_pinned_region_status(global_generation());
2531 }
2532 
2533 void ShenandoahHeap::assert_pinned_region_status(ShenandoahGeneration* generation) const {
2534   for (size_t i = 0; i < num_regions(); i++) {
2535     ShenandoahHeapRegion* r = get_region(i);
2536     if (generation->contains(r)) {
2537       assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
2538              "Region %zu pinning status is inconsistent", i);
2539     }
2540   }
2541 }
2542 #endif
2543 
2544 ConcurrentGCTimer* ShenandoahHeap::gc_timer() const {
2545   return _gc_timer;
2546 }
2547 
2548 void ShenandoahHeap::prepare_concurrent_roots() {
2549   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2550   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
2551   set_concurrent_strong_root_in_progress(!collection_set()->is_empty());
2552   set_concurrent_weak_root_in_progress(true);
2553   if (unload_classes()) {
2554     _unloader.prepare();
2555   }
2556 }
2557 
2558 void ShenandoahHeap::finish_concurrent_roots() {
2559   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2560   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
2561   if (unload_classes()) {
2562     _unloader.finish();
2563   }
2564 }
2565 
2566 #ifdef ASSERT
2567 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2568   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2569 
2570   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2571     // Use ParallelGCThreads inside safepoints
2572     assert(nworkers == ParallelGCThreads, "Use ParallelGCThreads (%u) within safepoint, not %u",
2573            ParallelGCThreads, nworkers);
2574   } else {
2575     // Use ConcGCThreads outside safepoints
2576     assert(nworkers == ConcGCThreads, "Use ConcGCThreads (%u) outside safepoints, %u",
2577            ConcGCThreads, nworkers);
2578   }
2579 }
2580 #endif
2581 
2582 ShenandoahVerifier* ShenandoahHeap::verifier() {
2583   guarantee(ShenandoahVerify, "Should be enabled");
2584   assert (_verifier != nullptr, "sanity");
2585   return _verifier;
2586 }
2587 
2588 template<bool CONCURRENT>
2589 class ShenandoahUpdateHeapRefsTask : public WorkerTask {
2590 private:
2591   ShenandoahHeap* _heap;
2592   ShenandoahRegionIterator* _regions;
2593 public:
2594   explicit ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) :
2595     WorkerTask("Shenandoah Update References"),
2596     _heap(ShenandoahHeap::heap()),
2597     _regions(regions) {
2598   }
2599 
2600   void work(uint worker_id) {
2601     if (CONCURRENT) {
2602       ShenandoahWorkerTimingsTracker timer(ShenandoahPhaseTimings::conc_update_refs, ShenandoahPhaseTimings::Work, worker_id, true);
2603       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2604       SuspendibleThreadSetJoiner stsj;
2605       do_work<ShenandoahConcUpdateRefsClosure>(worker_id);
2606     } else {
2607       ShenandoahWorkerTimingsTracker timer(ShenandoahPhaseTimings::degen_gc_update_refs, ShenandoahPhaseTimings::Work, worker_id, true);
2608       ShenandoahParallelWorkerSession worker_session(worker_id);
2609       do_work<ShenandoahNonConcUpdateRefsClosure>(worker_id);
2610     }
2611   }
2612 
2613 private:
2614   template<class T>
2615   void do_work(uint worker_id) {
2616     if (CONCURRENT && (worker_id == 0)) {
2617       // We ask the first worker to replenish the Mutator free set by moving regions previously reserved to hold the
2618       // results of evacuation.  These reserves are no longer necessary because evacuation has completed.
2619       size_t cset_regions = _heap->collection_set()->count();
2620 
2621       // Now that evacuation is done, we can reassign any regions that had been reserved to hold the results of evacuation
2622       // to the mutator free set.  At the end of GC, we will have cset_regions newly evacuated fully empty regions from
2623       // which we will be able to replenish the Collector free set and the OldCollector free set in preparation for the
2624       // next GC cycle.
2625       _heap->free_set()->move_regions_from_collector_to_mutator(cset_regions);
2626     }
2627     // If !CONCURRENT, there's no value in expanding Mutator free set
2628     T cl;
2629     ShenandoahHeapRegion* r = _regions->next();
2630     while (r != nullptr) {
2631       HeapWord* update_watermark = r->get_update_watermark();
2632       assert (update_watermark >= r->bottom(), "sanity");
2633       if (r->is_active() && !r->is_cset()) {
2634         _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2635       }
2636       if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
2637         return;
2638       }
2639       r = _regions->next();
2640     }
2641   }
2642 };
2643 
2644 void ShenandoahHeap::update_heap_references(ShenandoahGeneration* generation, bool concurrent) {
2645   assert(generation->is_global(), "Should only get global generation here");
2646   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2647 
2648   if (concurrent) {
2649     ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator);
2650     workers()->run_task(&task);
2651   } else {
2652     ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator);
2653     workers()->run_task(&task);
2654   }
2655 }
2656 
2657 void ShenandoahHeap::update_heap_region_states(bool concurrent) {
2658   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2659   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2660 
2661   {
2662     ShenandoahGCPhase phase(concurrent ?
2663                             ShenandoahPhaseTimings::final_update_refs_update_region_states :
2664                             ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states);
2665 
2666     final_update_refs_update_region_states();
2667 
2668     assert_pinned_region_status();
2669   }
2670 
2671   {
2672     ShenandoahGCPhase phase(concurrent ?
2673                             ShenandoahPhaseTimings::final_update_refs_trash_cset :
2674                             ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset);
2675     trash_cset_regions();
2676   }
2677 }
2678 
2679 void ShenandoahHeap::final_update_refs_update_region_states() {
2680   ShenandoahSynchronizePinnedRegionStates cl;
2681   parallel_heap_region_iterate(&cl);
2682 }
2683 
2684 void ShenandoahHeap::rebuild_free_set_within_phase() {
2685   ShenandoahHeapLocker locker(lock());
2686   size_t young_trashed_regions, old_trashed_regions, first_old_region, last_old_region, old_region_count;
2687   _free_set->prepare_to_rebuild(young_trashed_regions, old_trashed_regions, first_old_region, last_old_region, old_region_count);
2688   // If there are no old regions, first_old_region will be greater than last_old_region
2689   assert((first_old_region > last_old_region) ||
2690          ((last_old_region + 1 - first_old_region >= old_region_count) &&
2691           get_region(first_old_region)->is_old() && get_region(last_old_region)->is_old()),
2692          "sanity: old_region_count: %zu, first_old_region: %zu, last_old_region: %zu",
2693          old_region_count, first_old_region, last_old_region);
2694 
2695   if (mode()->is_generational()) {
2696 #ifdef ASSERT
2697     if (ShenandoahVerify) {
2698       verifier()->verify_before_rebuilding_free_set();
2699     }
2700 #endif
2701 
2702     // The computation of bytes_of_allocation_runway_before_gc_trigger is quite conservative so consider all of this
2703     // available for transfer to old. Note that transfer of humongous regions does not impact available.
2704     ShenandoahGenerationalHeap* gen_heap = ShenandoahGenerationalHeap::heap();
2705     size_t allocation_runway =
2706       gen_heap->young_generation()->heuristics()->bytes_of_allocation_runway_before_gc_trigger(young_trashed_regions);
2707     size_t max_transfer = MIN2(allocation_runway,
2708                                (gen_heap->young_generation()->free_unaffiliated_regions() + young_trashed_regions) *
2709                                ShenandoahHeapRegion::region_size_bytes());
2710     gen_heap->compute_old_generation_balance(max_transfer, old_trashed_regions, young_trashed_regions);
2711   }
2712   // Rebuild free set based on adjusted generation sizes.
2713   _free_set->finish_rebuild(young_trashed_regions, old_trashed_regions, old_region_count);
2714 
2715   if (mode()->is_generational()) {
2716     ShenandoahGenerationalHeap* gen_heap = ShenandoahGenerationalHeap::heap();
2717     ShenandoahOldGeneration* old_gen = gen_heap->old_generation();
2718     old_gen->heuristics()->evaluate_triggers(first_old_region, last_old_region, old_region_count, num_regions());
2719   }
2720 }
2721 
2722 void ShenandoahHeap::rebuild_free_set(bool concurrent) {
2723   ShenandoahGCPhase phase(concurrent ?
2724                           ShenandoahPhaseTimings::final_update_refs_rebuild_freeset :
2725                           ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset);
2726   rebuild_free_set_within_phase();
2727 }
2728 
2729 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2730   size_t slice = r->index() / _bitmap_regions_per_slice;
2731 
2732   size_t regions_from = _bitmap_regions_per_slice * slice;
2733   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2734   for (size_t g = regions_from; g < regions_to; g++) {
2735     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2736     if (skip_self && g == r->index()) continue;
2737     if (get_region(g)->is_committed()) {
2738       return true;
2739     }
2740   }
2741   return false;
2742 }
2743 
2744 void ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2745   shenandoah_assert_heaplocked();
2746   assert(!is_bitmap_region_special(), "Not for special memory");
2747 
2748   if (is_bitmap_slice_committed(r, true)) {
2749     // Some other region from the group is already committed, meaning the bitmap
2750     // slice is already committed, we exit right away.
2751     return;
2752   }
2753 
2754   // Commit the bitmap slice:
2755   size_t slice = r->index() / _bitmap_regions_per_slice;
2756   size_t off = _bitmap_bytes_per_slice * slice;
2757   size_t len = _bitmap_bytes_per_slice;
2758   char* start = (char*) _bitmap_region.start() + off;
2759 
2760   os::commit_memory_or_exit(start, len, false, "Unable to commit bitmap slice");
2761 
2762   if (AlwaysPreTouch) {
2763     os::pretouch_memory(start, start + len, _pretouch_bitmap_page_size);
2764   }
2765 }
2766 
2767 void ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2768   shenandoah_assert_heaplocked();
2769   assert(!is_bitmap_region_special(), "Not for special memory");
2770 
2771   if (is_bitmap_slice_committed(r, true)) {
2772     // Some other region from the group is still committed, meaning the bitmap
2773     // slice should stay committed, exit right away.
2774     return;
2775   }
2776 
2777   // Uncommit the bitmap slice:
2778   size_t slice = r->index() / _bitmap_regions_per_slice;
2779   size_t off = _bitmap_bytes_per_slice * slice;
2780   size_t len = _bitmap_bytes_per_slice;
2781 
2782   char* addr = (char*) _bitmap_region.start() + off;
2783   os::uncommit_memory(addr, len);
2784 }
2785 
2786 void ShenandoahHeap::forbid_uncommit() {
2787   if (_uncommit_thread != nullptr) {
2788     _uncommit_thread->forbid_uncommit();
2789   }
2790 }
2791 
2792 void ShenandoahHeap::allow_uncommit() {
2793   if (_uncommit_thread != nullptr) {
2794     _uncommit_thread->allow_uncommit();
2795   }
2796 }
2797 
2798 #ifdef ASSERT
2799 bool ShenandoahHeap::is_uncommit_in_progress() {
2800   if (_uncommit_thread != nullptr) {
2801     return _uncommit_thread->is_uncommit_in_progress();
2802   }
2803   return false;
2804 }
2805 #endif
2806 
2807 void ShenandoahHeap::safepoint_synchronize_begin() {
2808   StackWatermarkSet::safepoint_synchronize_begin();
2809   SuspendibleThreadSet::synchronize();
2810 }
2811 
2812 void ShenandoahHeap::safepoint_synchronize_end() {
2813   SuspendibleThreadSet::desynchronize();
2814 }
2815 
2816 void ShenandoahHeap::try_inject_alloc_failure() {
2817   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2818     _inject_alloc_failure.set();
2819     os::naked_short_sleep(1);
2820     if (cancelled_gc()) {
2821       log_info(gc)("Allocation failure was successfully injected");
2822     }
2823   }
2824 }
2825 
2826 bool ShenandoahHeap::should_inject_alloc_failure() {
2827   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2828 }
2829 
2830 void ShenandoahHeap::try_inject_pin() {
2831   assert(!ShenandoahSafepoint::is_at_shenandoah_safepoint(), "try_inject_pin() must be called outside a safepoint.");
2832   assert(active_generation() != nullptr, "Active generation must be set before we inject pins.");
2833   assert(is_concurrent_mark_in_progress() || active_generation()->is_mark_complete(),
2834          "try_inject_pin() requires marking is in progress or has completed.");
2835   if (ShenandoahPinRegionRate && !cancelled_gc() && ((uintx)(os::random() % 1000) < ShenandoahPinRegionRate) &&
2836       _injected_pin_count < MAX_INJECTED_PINS) {
2837     const size_t idx = os::random() % num_regions();
2838     ShenandoahHeapRegion* r = get_region(idx);
2839     if ((r->is_regular() || r->is_humongous_start()) && r->has_live()) {
2840       r->record_pin();
2841       _injected_pin_indices[_injected_pin_count] = idx;
2842       _injected_pin_count++;
2843     }
2844   }
2845 }
2846 
2847 void ShenandoahHeap::release_injected_pins() {
2848   if (_injected_pin_count == 0) {
2849     return;
2850   }
2851 
2852   assert(_injected_pin_count <= MAX_INJECTED_PINS,
2853          "Injected pin count: %u exceeds max: %u.", _injected_pin_count, MAX_INJECTED_PINS);
2854   for (uint i = 0; i < _injected_pin_count; i++) {
2855     const size_t idx = _injected_pin_indices[i];
2856     ShenandoahHeapRegion* r = get_region(idx);
2857     assert(r->pin_count() > 0, "Region %zu in tracker must contain a pin.", idx);
2858     r->record_unpin();
2859   }
2860   _injected_pin_count = 0;
2861 }
2862 
2863 void ShenandoahHeap::initialize_serviceability() {
2864   _memory_pool = new ShenandoahMemoryPool(this);
2865   _cycle_memory_manager.add_pool(_memory_pool);
2866   _stw_memory_manager.add_pool(_memory_pool);
2867 }
2868 
2869 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2870   GrowableArray<GCMemoryManager*> memory_managers(2);
2871   memory_managers.append(&_cycle_memory_manager);
2872   memory_managers.append(&_stw_memory_manager);
2873   return memory_managers;
2874 }
2875 
2876 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2877   GrowableArray<MemoryPool*> memory_pools(1);
2878   memory_pools.append(_memory_pool);
2879   return memory_pools;
2880 }
2881 
2882 MemoryUsage ShenandoahHeap::memory_usage() {
2883   return shenandoah_memory_usage(_initial_size, used(), committed(), max_capacity());
2884 }
2885 
2886 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2887   _heap(ShenandoahHeap::heap()),
2888   _index(0) {}
2889 
2890 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2891   _heap(heap),
2892   _index(0) {}
2893 
2894 void ShenandoahRegionIterator::reset() {
2895   _index.store_relaxed(0);
2896 }
2897 
2898 bool ShenandoahRegionIterator::has_next() const {
2899   return _index.load_relaxed() < _heap->num_regions();
2900 }
2901 
2902 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2903 #ifdef ASSERT
2904   assert(_liveness_cache != nullptr, "sanity");
2905   assert(worker_id < _max_workers, "sanity");
2906   for (uint i = 0; i < num_regions(); i++) {
2907     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2908   }
2909 #endif
2910   return _liveness_cache[worker_id];
2911 }
2912 
2913 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2914   assert(worker_id < _max_workers, "sanity");
2915   assert(_liveness_cache != nullptr, "sanity");
2916   ShenandoahLiveData* ld = _liveness_cache[worker_id];
2917   for (uint i = 0; i < num_regions(); i++) {
2918     ShenandoahLiveData live = ld[i];
2919     if (live > 0) {
2920       ShenandoahHeapRegion* r = get_region(i);
2921       r->increase_live_data_gc_words(live);
2922       ld[i] = 0;
2923     }
2924   }
2925 }
2926 
2927 bool ShenandoahHeap::requires_barriers(stackChunkOop obj) const {
2928   // Can not guarantee obj is deeply good.
2929   if (has_forwarded_objects()) {
2930     return true;
2931   }
2932 
2933   // Objects allocated after marking start are implicitly alive.
2934   if (is_concurrent_mark_in_progress() &&
2935       !marking_context()->allocated_after_mark_start(obj)) {
2936     return true;
2937   }
2938 
2939   // Nmethods referenced by stack chunk may need the barrier fixups.
2940   if (ShenandoahStackChunkGCData::is_different_epoch(obj)) {
2941     return true;
2942   }
2943 
2944   return false;
2945 }
2946 
2947 HeapWord* ShenandoahHeap::allocate_loaded_archive_space(size_t size) {
2948 #if INCLUDE_CDS_JAVA_HEAP
2949   // CDS wants a raw continuous memory range to load a bunch of objects itself.
2950   // This is an unusual request, since all requested regions should be regular, not humongous.
2951   //
2952   // CDS would guarantee no objects straddle multiple regions, as long as regions are as large
2953   // as MIN_GC_REGION_ALIGNMENT.
2954   guarantee(ShenandoahHeapRegion::region_size_bytes() >= AOTMappedHeapWriter::MIN_GC_REGION_ALIGNMENT, "Must be");
2955 
2956   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_cds(size);
2957   return allocate_memory(req);
2958 #else
2959   assert(false, "Archive heap loader should not be available, should not be here");
2960   return nullptr;
2961 #endif // INCLUDE_CDS_JAVA_HEAP
2962 }
2963 
2964 void ShenandoahHeap::complete_loaded_archive_space(MemRegion archive_space) {
2965   // Nothing to do here, except checking that heap looks fine.
2966 #ifdef ASSERT
2967   HeapWord* start = archive_space.start();
2968   HeapWord* end = archive_space.end();
2969 
2970   // No unclaimed space between the objects.
2971   // Objects are properly allocated in correct regions.
2972   HeapWord* cur = start;
2973   while (cur < end) {
2974     oop oop = cast_to_oop(cur);
2975     shenandoah_assert_in_correct_region(nullptr, oop);
2976     cur += oop->size();
2977   }
2978 
2979   // No unclaimed tail at the end of archive space.
2980   assert(cur == end,
2981          "Archive space should be fully used: " PTR_FORMAT " " PTR_FORMAT,
2982          p2i(cur), p2i(end));
2983 
2984   // All regions in contiguous space have good state.
2985   size_t begin_reg_idx = heap_region_index_containing(start);
2986   size_t end_reg_idx   = heap_region_index_containing(end);
2987 
2988   for (size_t idx = begin_reg_idx; idx <= end_reg_idx; idx++) {
2989     ShenandoahHeapRegion* r = get_region(idx);
2990     assert(r->is_regular(), "Must be regular");
2991     assert(r->is_young(), "Must be young");
2992     assert(idx == end_reg_idx || r->top() == r->end(),
2993            "All regions except the last one should be full: " PTR_FORMAT " " PTR_FORMAT,
2994            p2i(r->top()), p2i(r->end()));
2995     assert(idx != begin_reg_idx || r->bottom() == start,
2996            "Archive space start should be at the bottom of first region: " PTR_FORMAT " " PTR_FORMAT,
2997            p2i(r->bottom()), p2i(start));
2998     assert(idx != end_reg_idx || r->top() == end,
2999            "Archive space end should be at the top of last region: " PTR_FORMAT " " PTR_FORMAT,
3000            p2i(r->top()), p2i(end));
3001   }
3002 
3003 #endif
3004 }
3005 
3006 ShenandoahGeneration* ShenandoahHeap::generation_for(ShenandoahAffiliation affiliation) const {
3007   if (!mode()->is_generational()) {
3008     return global_generation();
3009   } else if (affiliation == YOUNG_GENERATION) {
3010     return young_generation();
3011   } else if (affiliation == OLD_GENERATION) {
3012     return old_generation();
3013   }
3014 
3015   ShouldNotReachHere();
3016   return nullptr;
3017 }
3018 
3019 void ShenandoahHeap::log_heap_status(const char* msg) const {
3020   if (mode()->is_generational()) {
3021     young_generation()->log_status(msg);
3022     old_generation()->log_status(msg);
3023   } else {
3024     global_generation()->log_status(msg);
3025   }
3026 }
3027 
3028 ShenandoahHeapLocker::ShenandoahHeapLocker(ShenandoahHeapLock* lock, bool allow_block_for_safepoint) : _lock(lock) {
3029 #ifdef ASSERT
3030   ShenandoahFreeSet* free_set = ShenandoahHeap::heap()->free_set();
3031   // free_set is nullptr only at pre-initialized state
3032   assert(free_set == nullptr || !free_set->rebuild_lock()->owned_by_self(), "Dead lock, can't acquire heap lock while holding free-set rebuild lock");
3033   assert(_lock != nullptr, "Must not");
3034 #endif
3035   _lock->lock(allow_block_for_safepoint);
3036 }