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