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