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