1 /*
   2  * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2013, 2022, Red Hat, Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "memory/allocation.hpp"
  28 #include "memory/universe.hpp"
  29 
  30 #include "gc/shared/gcArguments.hpp"
  31 #include "gc/shared/gcTimer.hpp"
  32 #include "gc/shared/gcTraceTime.inline.hpp"
  33 #include "gc/shared/locationPrinter.inline.hpp"
  34 #include "gc/shared/memAllocator.hpp"
  35 #include "gc/shared/plab.hpp"
  36 #include "gc/shared/tlab_globals.hpp"
  37 
  38 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  39 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  40 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  41 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  42 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
  43 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  44 #include "gc/shenandoah/shenandoahControlThread.hpp"
  45 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  46 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  47 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  48 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  49 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  50 #include "gc/shenandoah/shenandoahInitLogger.hpp"
  51 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  52 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
  53 #include "gc/shenandoah/shenandoahMetrics.hpp"
  54 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  55 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  56 #include "gc/shenandoah/shenandoahPacer.inline.hpp"
  57 #include "gc/shenandoah/shenandoahPadding.hpp"
  58 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
  59 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  60 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  61 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  62 #include "gc/shenandoah/shenandoahUtils.hpp"
  63 #include "gc/shenandoah/shenandoahVerifier.hpp"
  64 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
  65 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  66 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  67 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  68 #include "gc/shenandoah/mode/shenandoahIUMode.hpp"
  69 #include "gc/shenandoah/mode/shenandoahPassiveMode.hpp"
  70 #include "gc/shenandoah/mode/shenandoahSATBMode.hpp"
  71 #if INCLUDE_JFR
  72 #include "gc/shenandoah/shenandoahJfrSupport.hpp"
  73 #endif
  74 
  75 #include "classfile/systemDictionary.hpp"
  76 #include "code/codeCache.hpp"
  77 #include "memory/classLoaderMetaspace.hpp"
  78 #include "memory/metaspaceUtils.hpp"
  79 #include "oops/compressedOops.inline.hpp"
  80 #include "prims/jvmtiTagMap.hpp"
  81 #include "runtime/atomic.hpp"
  82 #include "runtime/globals.hpp"
  83 #include "runtime/interfaceSupport.inline.hpp"
  84 #include "runtime/java.hpp"
  85 #include "runtime/orderAccess.hpp"
  86 #include "runtime/safepointMechanism.hpp"
  87 #include "runtime/vmThread.hpp"
  88 #include "services/mallocTracker.hpp"
  89 #include "services/memTracker.hpp"
  90 #include "utilities/events.hpp"
  91 #include "utilities/powerOfTwo.hpp"
  92 
  93 class ShenandoahPretouchHeapTask : public WorkerTask {
  94 private:
  95   ShenandoahRegionIterator _regions;
  96   const size_t _page_size;
  97 public:
  98   ShenandoahPretouchHeapTask(size_t page_size) :
  99     WorkerTask("Shenandoah Pretouch Heap"),
 100     _page_size(page_size) {}
 101 
 102   virtual void work(uint worker_id) {
 103     ShenandoahHeapRegion* r = _regions.next();
 104     while (r != nullptr) {
 105       if (r->is_committed()) {
 106         os::pretouch_memory(r->bottom(), r->end(), _page_size);
 107       }
 108       r = _regions.next();
 109     }
 110   }
 111 };
 112 
 113 class ShenandoahPretouchBitmapTask : public WorkerTask {
 114 private:
 115   ShenandoahRegionIterator _regions;
 116   char* _bitmap_base;
 117   const size_t _bitmap_size;
 118   const size_t _page_size;
 119 public:
 120   ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :
 121     WorkerTask("Shenandoah Pretouch Bitmap"),
 122     _bitmap_base(bitmap_base),
 123     _bitmap_size(bitmap_size),
 124     _page_size(page_size) {}
 125 
 126   virtual void work(uint worker_id) {
 127     ShenandoahHeapRegion* r = _regions.next();
 128     while (r != nullptr) {
 129       size_t start = r->index()       * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 130       size_t end   = (r->index() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 131       assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size);
 132 
 133       if (r->is_committed()) {
 134         os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
 135       }
 136 
 137       r = _regions.next();
 138     }
 139   }
 140 };
 141 
 142 jint ShenandoahHeap::initialize() {
 143   //
 144   // Figure out heap sizing
 145   //
 146 
 147   size_t init_byte_size = InitialHeapSize;
 148   size_t min_byte_size  = MinHeapSize;
 149   size_t max_byte_size  = MaxHeapSize;
 150   size_t heap_alignment = HeapAlignment;
 151 
 152   size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 153 
 154   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
 155   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
 156 
 157   _num_regions = ShenandoahHeapRegion::region_count();
 158   assert(_num_regions == (max_byte_size / reg_size_bytes),
 159          "Regions should cover entire heap exactly: " SIZE_FORMAT " != " SIZE_FORMAT "/" SIZE_FORMAT,
 160          _num_regions, max_byte_size, reg_size_bytes);
 161 
 162   // Now we know the number of regions, initialize the heuristics.
 163   initialize_heuristics();
 164 
 165   size_t num_committed_regions = init_byte_size / reg_size_bytes;
 166   num_committed_regions = MIN2(num_committed_regions, _num_regions);
 167   assert(num_committed_regions <= _num_regions, "sanity");
 168   _initial_size = num_committed_regions * reg_size_bytes;
 169 
 170   size_t num_min_regions = min_byte_size / reg_size_bytes;
 171   num_min_regions = MIN2(num_min_regions, _num_regions);
 172   assert(num_min_regions <= _num_regions, "sanity");
 173   _minimum_size = num_min_regions * reg_size_bytes;
 174 
 175   // Default to max heap size.
 176   _soft_max_size = _num_regions * reg_size_bytes;
 177 
 178   _committed = _initial_size;
 179 
 180   size_t heap_page_size   = UseLargePages ? os::large_page_size() : os::vm_page_size();
 181   size_t bitmap_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
 182   size_t region_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size();
 183 
 184   //
 185   // Reserve and commit memory for heap
 186   //
 187 
 188   ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
 189   initialize_reserved_region(heap_rs);
 190   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
 191   _heap_region_special = heap_rs.special();
 192 
 193   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 194          "Misaligned heap: " PTR_FORMAT, p2i(base()));
 195 
 196 #if SHENANDOAH_OPTIMIZED_MARKTASK
 197   // The optimized ShenandoahMarkTask takes some bits away from the full object bits.
 198   // Fail if we ever attempt to address more than we can.
 199   if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) {
 200     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
 201                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
 202                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
 203                 p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable());
 204     vm_exit_during_initialization("Fatal Error", buf);
 205   }
 206 #endif
 207 
 208   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
 209   if (!_heap_region_special) {
 210     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
 211                               "Cannot commit heap memory");
 212   }
 213 
 214   //
 215   // Reserve and commit memory for bitmap(s)
 216   //
 217 
 218   _bitmap_size = ShenandoahMarkBitMap::compute_size(heap_rs.size());
 219   _bitmap_size = align_up(_bitmap_size, bitmap_page_size);
 220 
 221   size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor();
 222 
 223   guarantee(bitmap_bytes_per_region != 0,
 224             "Bitmap bytes per region should not be zero");
 225   guarantee(is_power_of_2(bitmap_bytes_per_region),
 226             "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
 227 
 228   if (bitmap_page_size > bitmap_bytes_per_region) {
 229     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
 230     _bitmap_bytes_per_slice = bitmap_page_size;
 231   } else {
 232     _bitmap_regions_per_slice = 1;
 233     _bitmap_bytes_per_slice = bitmap_bytes_per_region;
 234   }
 235 
 236   guarantee(_bitmap_regions_per_slice >= 1,
 237             "Should have at least one region per slice: " SIZE_FORMAT,
 238             _bitmap_regions_per_slice);
 239 
 240   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
 241             "Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
 242             _bitmap_bytes_per_slice, bitmap_page_size);
 243 
 244   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
 245   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
 246   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 247   _bitmap_region_special = bitmap.special();
 248 
 249   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
 250                               align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
 251   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
 252   if (!_bitmap_region_special) {
 253     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
 254                               "Cannot commit bitmap memory");
 255   }
 256 
 257   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions, _max_workers);
 258 
 259   if (ShenandoahVerify) {
 260     ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
 261     if (!verify_bitmap.special()) {
 262       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
 263                                 "Cannot commit verification bitmap memory");
 264     }
 265     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 266     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 267     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 268     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 269   }
 270 
 271   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 272   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
 273   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
 274   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 275   _aux_bitmap_region_special = aux_bitmap.special();
 276   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 277 
 278   //
 279   // Create regions and region sets
 280   //
 281   size_t region_align = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);
 282   size_t region_storage_size = align_up(region_align * _num_regions, region_page_size);
 283   region_storage_size = align_up(region_storage_size, os::vm_allocation_granularity());
 284 
 285   ReservedSpace region_storage(region_storage_size, region_page_size);
 286   MemTracker::record_virtual_memory_type(region_storage.base(), mtGC);
 287   if (!region_storage.special()) {
 288     os::commit_memory_or_exit(region_storage.base(), region_storage_size, region_page_size, false,
 289                               "Cannot commit region memory");
 290   }
 291 
 292   // Try to fit the collection set bitmap at lower addresses. This optimizes code generation for cset checks.
 293   // Go up until a sensible limit (subject to encoding constraints) and try to reserve the space there.
 294   // If not successful, bite a bullet and allocate at whatever address.
 295   {
 296     size_t cset_align = MAX2<size_t>(os::vm_page_size(), os::vm_allocation_granularity());
 297     size_t cset_size = align_up(((size_t) sh_rs.base() + sh_rs.size()) >> ShenandoahHeapRegion::region_size_bytes_shift(), cset_align);
 298 
 299     uintptr_t min = round_up_power_of_2(cset_align);
 300     uintptr_t max = (1u << 30u);
 301 
 302     for (uintptr_t addr = min; addr <= max; addr <<= 1u) {
 303       char* req_addr = (char*)addr;
 304       assert(is_aligned(req_addr, cset_align), "Should be aligned");
 305       ReservedSpace cset_rs(cset_size, cset_align, os::vm_page_size(), req_addr);
 306       if (cset_rs.is_reserved()) {
 307         assert(cset_rs.base() == req_addr, "Allocated where requested: " PTR_FORMAT ", " PTR_FORMAT, p2i(cset_rs.base()), addr);
 308         _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 309         break;
 310       }
 311     }
 312 
 313     if (_collection_set == nullptr) {
 314       ReservedSpace cset_rs(cset_size, cset_align, os::vm_page_size());
 315       _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 316     }
 317   }
 318 
 319   _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
 320   _free_set = new ShenandoahFreeSet(this, _num_regions);
 321 
 322   {
 323     ShenandoahHeapLocker locker(lock());
 324 
 325     for (size_t i = 0; i < _num_regions; i++) {
 326       HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i;
 327       bool is_committed = i < num_committed_regions;
 328       void* loc = region_storage.base() + i * region_align;
 329 
 330       ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed);
 331       assert(is_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity");
 332 
 333       _marking_context->initialize_top_at_mark_start(r);
 334       _regions[i] = r;
 335       assert(!collection_set()->is_in(i), "New region should not be in collection set");
 336     }
 337 
 338     // Initialize to complete
 339     _marking_context->mark_complete();
 340 
 341     _free_set->rebuild();
 342   }
 343 
 344   if (AlwaysPreTouch) {
 345     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
 346     // before initialize() below zeroes it with initializing thread. For any given region,
 347     // we touch the region and the corresponding bitmaps from the same thread.
 348     ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
 349 
 350     _pretouch_heap_page_size = heap_page_size;
 351     _pretouch_bitmap_page_size = bitmap_page_size;
 352 
 353 #ifdef LINUX
 354     // UseTransparentHugePages would madvise that backing memory can be coalesced into huge
 355     // pages. But, the kernel needs to know that every small page is used, in order to coalesce
 356     // them into huge one. Therefore, we need to pretouch with smaller pages.
 357     if (UseTransparentHugePages) {
 358       _pretouch_heap_page_size = (size_t)os::vm_page_size();
 359       _pretouch_bitmap_page_size = (size_t)os::vm_page_size();
 360     }
 361 #endif
 362 
 363     // OS memory managers may want to coalesce back-to-back pages. Make their jobs
 364     // simpler by pre-touching continuous spaces (heap and bitmap) separately.
 365 
 366     ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, _pretouch_bitmap_page_size);
 367     _workers->run_task(&bcl);
 368 
 369     ShenandoahPretouchHeapTask hcl(_pretouch_heap_page_size);
 370     _workers->run_task(&hcl);
 371   }
 372 
 373   //
 374   // Initialize the rest of GC subsystems
 375   //
 376 
 377   _liveness_cache = NEW_C_HEAP_ARRAY(ShenandoahLiveData*, _max_workers, mtGC);
 378   for (uint worker = 0; worker < _max_workers; worker++) {
 379     _liveness_cache[worker] = NEW_C_HEAP_ARRAY(ShenandoahLiveData, _num_regions, mtGC);
 380     Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(ShenandoahLiveData));
 381   }
 382 
 383   // There should probably be Shenandoah-specific options for these,
 384   // just as there are G1-specific options.
 385   {
 386     ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
 387     satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
 388     satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
 389   }
 390 
 391   _monitoring_support = new ShenandoahMonitoringSupport(this);
 392   _phase_timings = new ShenandoahPhaseTimings(max_workers());
 393   ShenandoahCodeRoots::initialize();
 394 
 395   if (ShenandoahPacing) {
 396     _pacer = new ShenandoahPacer(this);
 397     _pacer->setup_for_idle();
 398   } else {
 399     _pacer = nullptr;
 400   }
 401 
 402   _control_thread = new ShenandoahControlThread();
 403 
 404   ShenandoahInitLogger::print();
 405 
 406   return JNI_OK;
 407 }
 408 
 409 void ShenandoahHeap::initialize_mode() {
 410   if (ShenandoahGCMode != nullptr) {
 411     if (strcmp(ShenandoahGCMode, "satb") == 0) {
 412       _gc_mode = new ShenandoahSATBMode();
 413     } else if (strcmp(ShenandoahGCMode, "iu") == 0) {
 414       _gc_mode = new ShenandoahIUMode();
 415     } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
 416       _gc_mode = new ShenandoahPassiveMode();
 417     } else {
 418       vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
 419     }
 420   } else {
 421     vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option (null)");
 422   }
 423   _gc_mode->initialize_flags();
 424   if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 425     vm_exit_during_initialization(
 426             err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 427                     _gc_mode->name()));
 428   }
 429   if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {
 430     vm_exit_during_initialization(
 431             err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 432                     _gc_mode->name()));
 433   }
 434 }
 435 
 436 void ShenandoahHeap::initialize_heuristics() {
 437   assert(_gc_mode != nullptr, "Must be initialized");
 438   _heuristics = _gc_mode->initialize_heuristics();
 439 
 440   if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 441     vm_exit_during_initialization(
 442             err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 443                     _heuristics->name()));
 444   }
 445   if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {
 446     vm_exit_during_initialization(
 447             err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 448                     _heuristics->name()));
 449   }
 450 }
 451 
 452 #ifdef _MSC_VER
 453 #pragma warning( push )
 454 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 455 #endif
 456 
 457 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 458   CollectedHeap(),
 459   _initial_size(0),
 460   _used(0),
 461   _committed(0),
 462   _bytes_allocated_since_gc_start(0),
 463   _max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),
 464   _workers(nullptr),
 465   _safepoint_workers(nullptr),
 466   _heap_region_special(false),
 467   _num_regions(0),
 468   _regions(nullptr),
 469   _update_refs_iterator(this),
 470   _control_thread(nullptr),
 471   _shenandoah_policy(policy),
 472   _gc_mode(nullptr),
 473   _heuristics(nullptr),
 474   _free_set(nullptr),
 475   _pacer(nullptr),
 476   _verifier(nullptr),
 477   _phase_timings(nullptr),
 478   _monitoring_support(nullptr),
 479   _memory_pool(nullptr),
 480   _stw_memory_manager("Shenandoah Pauses"),
 481   _cycle_memory_manager("Shenandoah Cycles"),
 482   _gc_timer(new ConcurrentGCTimer()),
 483   _soft_ref_policy(),
 484   _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),
 485   _ref_processor(new ShenandoahReferenceProcessor(MAX2(_max_workers, 1U))),
 486   _marking_context(nullptr),
 487   _bitmap_size(0),
 488   _bitmap_regions_per_slice(0),
 489   _bitmap_bytes_per_slice(0),
 490   _bitmap_region_special(false),
 491   _aux_bitmap_region_special(false),
 492   _liveness_cache(nullptr),
 493   _collection_set(nullptr)
 494 {
 495   // Initialize GC mode early, so we can adjust barrier support
 496   initialize_mode();
 497   BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this));
 498 
 499   _max_workers = MAX2(_max_workers, 1U);
 500   _workers = new ShenandoahWorkerThreads("Shenandoah GC Threads", _max_workers);
 501   if (_workers == nullptr) {
 502     vm_exit_during_initialization("Failed necessary allocation.");
 503   } else {
 504     _workers->initialize_workers();
 505   }
 506 
 507   if (ParallelGCThreads > 1) {
 508     _safepoint_workers = new ShenandoahWorkerThreads("Safepoint Cleanup Thread",
 509                                                 ParallelGCThreads);
 510     _safepoint_workers->initialize_workers();
 511   }
 512 }
 513 
 514 #ifdef _MSC_VER
 515 #pragma warning( pop )
 516 #endif
 517 
 518 class ShenandoahResetBitmapTask : public WorkerTask {
 519 private:
 520   ShenandoahRegionIterator _regions;
 521 
 522 public:
 523   ShenandoahResetBitmapTask() :
 524     WorkerTask("Shenandoah Reset Bitmap") {}
 525 
 526   void work(uint worker_id) {
 527     ShenandoahHeapRegion* region = _regions.next();
 528     ShenandoahHeap* heap = ShenandoahHeap::heap();
 529     ShenandoahMarkingContext* const ctx = heap->marking_context();
 530     while (region != nullptr) {
 531       if (heap->is_bitmap_slice_committed(region)) {
 532         ctx->clear_bitmap(region);
 533       }
 534       region = _regions.next();
 535     }
 536   }
 537 };
 538 
 539 void ShenandoahHeap::reset_mark_bitmap() {
 540   assert_gc_workers(_workers->active_workers());
 541   mark_incomplete_marking_context();
 542 
 543   ShenandoahResetBitmapTask task;
 544   _workers->run_task(&task);
 545 }
 546 
 547 void ShenandoahHeap::print_on(outputStream* st) const {
 548   st->print_cr("Shenandoah Heap");
 549   st->print_cr(" " SIZE_FORMAT "%s max, " SIZE_FORMAT "%s soft max, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",
 550                byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),
 551                byte_size_in_proper_unit(soft_max_capacity()), proper_unit_for_byte_size(soft_max_capacity()),
 552                byte_size_in_proper_unit(committed()),    proper_unit_for_byte_size(committed()),
 553                byte_size_in_proper_unit(used()),         proper_unit_for_byte_size(used()));
 554   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",
 555                num_regions(),
 556                byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),
 557                proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));
 558 
 559   st->print("Status: ");
 560   if (has_forwarded_objects())                 st->print("has forwarded objects, ");
 561   if (is_concurrent_mark_in_progress())        st->print("marking, ");
 562   if (is_evacuation_in_progress())             st->print("evacuating, ");
 563   if (is_update_refs_in_progress())            st->print("updating refs, ");
 564   if (is_degenerated_gc_in_progress())         st->print("degenerated gc, ");
 565   if (is_full_gc_in_progress())                st->print("full gc, ");
 566   if (is_full_gc_move_in_progress())           st->print("full gc move, ");
 567   if (is_concurrent_weak_root_in_progress())   st->print("concurrent weak roots, ");
 568   if (is_concurrent_strong_root_in_progress() &&
 569       !is_concurrent_weak_root_in_progress())  st->print("concurrent strong roots, ");
 570 
 571   if (cancelled_gc()) {
 572     st->print("cancelled");
 573   } else {
 574     st->print("not cancelled");
 575   }
 576   st->cr();
 577 
 578   st->print_cr("Reserved region:");
 579   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
 580                p2i(reserved_region().start()),
 581                p2i(reserved_region().end()));
 582 
 583   ShenandoahCollectionSet* cset = collection_set();
 584   st->print_cr("Collection set:");
 585   if (cset != nullptr) {
 586     st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));
 587     st->print_cr(" - map (biased):  " PTR_FORMAT, p2i(cset->biased_map_address()));
 588   } else {
 589     st->print_cr(" (null)");
 590   }
 591 
 592   st->cr();
 593   MetaspaceUtils::print_on(st);
 594 
 595   if (Verbose) {
 596     st->cr();
 597     print_heap_regions_on(st);
 598   }
 599 }
 600 
 601 class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {
 602 public:
 603   void do_thread(Thread* thread) {
 604     assert(thread != nullptr, "Sanity");
 605     assert(thread->is_Worker_thread(), "Only worker thread expected");
 606     ShenandoahThreadLocalData::initialize_gclab(thread);
 607   }
 608 };
 609 
 610 void ShenandoahHeap::post_initialize() {
 611   CollectedHeap::post_initialize();
 612   MutexLocker ml(Threads_lock);
 613 
 614   ShenandoahInitWorkerGCLABClosure init_gclabs;
 615   _workers->threads_do(&init_gclabs);
 616 
 617   // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 618   // Now, we will let WorkerThreads to initialize gclab when new worker is created.
 619   _workers->set_initialize_gclab();
 620   if (_safepoint_workers != nullptr) {
 621     _safepoint_workers->threads_do(&init_gclabs);
 622     _safepoint_workers->set_initialize_gclab();
 623   }
 624 
 625   _heuristics->initialize();
 626 
 627   JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers());
 628 }
 629 
 630 size_t ShenandoahHeap::used() const {
 631   return Atomic::load(&_used);
 632 }
 633 
 634 size_t ShenandoahHeap::committed() const {
 635   return Atomic::load(&_committed);
 636 }
 637 
 638 void ShenandoahHeap::increase_committed(size_t bytes) {
 639   shenandoah_assert_heaplocked_or_safepoint();
 640   _committed += bytes;
 641 }
 642 
 643 void ShenandoahHeap::decrease_committed(size_t bytes) {
 644   shenandoah_assert_heaplocked_or_safepoint();
 645   _committed -= bytes;
 646 }
 647 
 648 void ShenandoahHeap::increase_used(size_t bytes) {
 649   Atomic::add(&_used, bytes, memory_order_relaxed);
 650 }
 651 
 652 void ShenandoahHeap::set_used(size_t bytes) {
 653   Atomic::store(&_used, bytes);
 654 }
 655 
 656 void ShenandoahHeap::decrease_used(size_t bytes) {
 657   assert(used() >= bytes, "never decrease heap size by more than we've left");
 658   Atomic::sub(&_used, bytes, memory_order_relaxed);
 659 }
 660 
 661 void ShenandoahHeap::increase_allocated(size_t bytes) {
 662   Atomic::add(&_bytes_allocated_since_gc_start, bytes, memory_order_relaxed);
 663 }
 664 
 665 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
 666   size_t bytes = words * HeapWordSize;
 667   if (!waste) {
 668     increase_used(bytes);
 669   }
 670   increase_allocated(bytes);
 671   if (ShenandoahPacing) {
 672     control_thread()->pacing_notify_alloc(words);
 673     if (waste) {
 674       pacer()->claim_for_alloc(words, true);
 675     }
 676   }
 677 }
 678 
 679 size_t ShenandoahHeap::capacity() const {
 680   return committed();
 681 }
 682 
 683 size_t ShenandoahHeap::max_capacity() const {
 684   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 685 }
 686 
 687 size_t ShenandoahHeap::soft_max_capacity() const {
 688   size_t v = Atomic::load(&_soft_max_size);
 689   assert(min_capacity() <= v && v <= max_capacity(),
 690          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 691          min_capacity(), v, max_capacity());
 692   return v;
 693 }
 694 
 695 void ShenandoahHeap::set_soft_max_capacity(size_t v) {
 696   assert(min_capacity() <= v && v <= max_capacity(),
 697          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 698          min_capacity(), v, max_capacity());
 699   Atomic::store(&_soft_max_size, v);
 700 }
 701 
 702 size_t ShenandoahHeap::min_capacity() const {
 703   return _minimum_size;
 704 }
 705 
 706 size_t ShenandoahHeap::initial_capacity() const {
 707   return _initial_size;
 708 }
 709 
 710 bool ShenandoahHeap::is_in(const void* p) const {
 711   HeapWord* heap_base = (HeapWord*) base();
 712   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
 713   return p >= heap_base && p < last_region_end;
 714 }
 715 
 716 void ShenandoahHeap::op_uncommit(double shrink_before, size_t shrink_until) {
 717   assert (ShenandoahUncommit, "should be enabled");
 718 
 719   // Application allocates from the beginning of the heap, and GC allocates at
 720   // the end of it. It is more efficient to uncommit from the end, so that applications
 721   // could enjoy the near committed regions. GC allocations are much less frequent,
 722   // and therefore can accept the committing costs.
 723 
 724   size_t count = 0;
 725   for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
 726     ShenandoahHeapRegion* r = get_region(i - 1);
 727     if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
 728       ShenandoahHeapLocker locker(lock());
 729       if (r->is_empty_committed()) {
 730         if (committed() < shrink_until + ShenandoahHeapRegion::region_size_bytes()) {
 731           break;
 732         }
 733 
 734         r->make_uncommitted();
 735         count++;
 736       }
 737     }
 738     SpinPause(); // allow allocators to take the lock
 739   }
 740 
 741   if (count > 0) {
 742     control_thread()->notify_heap_changed();
 743   }
 744 }
 745 
 746 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 747   // New object should fit the GCLAB size
 748   size_t min_size = MAX2(size, PLAB::min_size());
 749 
 750   // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
 751   size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
 752   new_size = MIN2(new_size, PLAB::max_size());
 753   new_size = MAX2(new_size, PLAB::min_size());
 754 
 755   // Record new heuristic value even if we take any shortcut. This captures
 756   // the case when moderately-sized objects always take a shortcut. At some point,
 757   // heuristics should catch up with them.
 758   ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
 759 
 760   if (new_size < size) {
 761     // New size still does not fit the object. Fall back to shared allocation.
 762     // This avoids retiring perfectly good GCLABs, when we encounter a large object.
 763     return nullptr;
 764   }
 765 
 766   // Retire current GCLAB, and allocate a new one.
 767   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
 768   gclab->retire();
 769 
 770   size_t actual_size = 0;
 771   HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);
 772   if (gclab_buf == nullptr) {
 773     return nullptr;
 774   }
 775 
 776   assert (size <= actual_size, "allocation should fit");
 777 
 778   if (ZeroTLAB) {
 779     // ..and clear it.
 780     Copy::zero_to_words(gclab_buf, actual_size);
 781   } else {
 782     // ...and zap just allocated object.
 783 #ifdef ASSERT
 784     // Skip mangling the space corresponding to the object header to
 785     // ensure that the returned space is not considered parsable by
 786     // any concurrent GC thread.
 787     size_t hdr_size = oopDesc::header_size();
 788     Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 789 #endif // ASSERT
 790   }
 791   gclab->set_buf(gclab_buf, actual_size);
 792   return gclab->allocate(size);
 793 }
 794 
 795 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
 796                                             size_t requested_size,
 797                                             size_t* actual_size) {
 798   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
 799   HeapWord* res = allocate_memory(req);
 800   if (res != nullptr) {
 801     *actual_size = req.actual_size();
 802   } else {
 803     *actual_size = 0;
 804   }
 805   return res;
 806 }
 807 
 808 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
 809                                              size_t word_size,
 810                                              size_t* actual_size) {
 811   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
 812   HeapWord* res = allocate_memory(req);
 813   if (res != nullptr) {
 814     *actual_size = req.actual_size();
 815   } else {
 816     *actual_size = 0;
 817   }
 818   return res;
 819 }
 820 
 821 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {
 822   intptr_t pacer_epoch = 0;
 823   bool in_new_region = false;
 824   HeapWord* result = nullptr;
 825 
 826   if (req.is_mutator_alloc()) {
 827     if (ShenandoahPacing) {
 828       pacer()->pace_for_alloc(req.size());
 829       pacer_epoch = pacer()->epoch();
 830     }
 831 
 832     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
 833       result = allocate_memory_under_lock(req, in_new_region);
 834     }
 835 
 836     // Allocation failed, block until control thread reacted, then retry allocation.
 837     //
 838     // It might happen that one of the threads requesting allocation would unblock
 839     // way later after GC happened, only to fail the second allocation, because
 840     // other threads have already depleted the free storage. In this case, a better
 841     // strategy is to try again, as long as GC makes progress (or until at least
 842     // one full GC has completed).
 843     size_t original_count = shenandoah_policy()->full_gc_count();
 844     while (result == nullptr
 845         && (_progress_last_gc.is_set() || original_count == shenandoah_policy()->full_gc_count())) {
 846       control_thread()->handle_alloc_failure(req);
 847       result = allocate_memory_under_lock(req, in_new_region);
 848     }
 849   } else {
 850     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
 851     result = allocate_memory_under_lock(req, in_new_region);
 852     // Do not call handle_alloc_failure() here, because we cannot block.
 853     // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
 854   }
 855 
 856   if (in_new_region) {
 857     control_thread()->notify_heap_changed();
 858   }
 859 
 860   if (result != nullptr) {
 861     size_t requested = req.size();
 862     size_t actual = req.actual_size();
 863 
 864     assert (req.is_lab_alloc() || (requested == actual),
 865             "Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
 866             ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
 867 
 868     if (req.is_mutator_alloc()) {
 869       notify_mutator_alloc_words(actual, false);
 870 
 871       // If we requested more than we were granted, give the rest back to pacer.
 872       // This only matters if we are in the same pacing epoch: do not try to unpace
 873       // over the budget for the other phase.
 874       if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
 875         pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
 876       }
 877     } else {
 878       increase_used(actual*HeapWordSize);
 879     }
 880   }
 881 
 882   return result;
 883 }
 884 
 885 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {
 886   ShenandoahHeapLocker locker(lock());
 887   return _free_set->allocate(req, in_new_region);
 888 }
 889 
 890 HeapWord* ShenandoahHeap::mem_allocate(size_t size,
 891                                         bool*  gc_overhead_limit_was_exceeded) {
 892   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
 893   return allocate_memory(req);
 894 }
 895 
 896 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
 897                                                              size_t size,
 898                                                              Metaspace::MetadataType mdtype) {
 899   MetaWord* result;
 900 
 901   // Inform metaspace OOM to GC heuristics if class unloading is possible.
 902   if (heuristics()->can_unload_classes()) {
 903     ShenandoahHeuristics* h = heuristics();
 904     h->record_metaspace_oom();
 905   }
 906 
 907   // Expand and retry allocation
 908   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
 909   if (result != nullptr) {
 910     return result;
 911   }
 912 
 913   // Start full GC
 914   collect(GCCause::_metadata_GC_clear_soft_refs);
 915 
 916   // Retry allocation
 917   result = loader_data->metaspace_non_null()->allocate(size, mdtype);
 918   if (result != nullptr) {
 919     return result;
 920   }
 921 
 922   // Expand and retry allocation
 923   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
 924   if (result != nullptr) {
 925     return result;
 926   }
 927 
 928   // Out of memory
 929   return nullptr;
 930 }
 931 
 932 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
 933 private:
 934   ShenandoahHeap* const _heap;
 935   Thread* const _thread;
 936 public:
 937   ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
 938     _heap(heap), _thread(Thread::current()) {}
 939 
 940   void do_object(oop p) {
 941     shenandoah_assert_marked(nullptr, p);
 942     if (!p->is_forwarded()) {
 943       _heap->evacuate_object(p, _thread);
 944     }
 945   }
 946 };
 947 
 948 class ShenandoahEvacuationTask : public WorkerTask {
 949 private:
 950   ShenandoahHeap* const _sh;
 951   ShenandoahCollectionSet* const _cs;
 952   bool _concurrent;
 953 public:
 954   ShenandoahEvacuationTask(ShenandoahHeap* sh,
 955                            ShenandoahCollectionSet* cs,
 956                            bool concurrent) :
 957     WorkerTask("Shenandoah Evacuation"),
 958     _sh(sh),
 959     _cs(cs),
 960     _concurrent(concurrent)
 961   {}
 962 
 963   void work(uint worker_id) {
 964     if (_concurrent) {
 965       ShenandoahConcurrentWorkerSession worker_session(worker_id);
 966       ShenandoahSuspendibleThreadSetJoiner stsj;
 967       ShenandoahEvacOOMScope oom_evac_scope;
 968       do_work();
 969     } else {
 970       ShenandoahParallelWorkerSession worker_session(worker_id);
 971       ShenandoahEvacOOMScope oom_evac_scope;
 972       do_work();
 973     }
 974   }
 975 
 976 private:
 977   void do_work() {
 978     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
 979     ShenandoahHeapRegion* r;
 980     while ((r =_cs->claim_next()) != nullptr) {
 981       assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index());
 982       _sh->marked_object_iterate(r, &cl);
 983 
 984       if (ShenandoahPacing) {
 985         _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
 986       }
 987 
 988       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
 989         break;
 990       }
 991     }
 992   }
 993 };
 994 
 995 void ShenandoahHeap::evacuate_collection_set(bool concurrent) {
 996   ShenandoahEvacuationTask task(this, _collection_set, concurrent);
 997   workers()->run_task(&task);
 998 }
 999 
1000 void ShenandoahHeap::trash_cset_regions() {
1001   ShenandoahHeapLocker locker(lock());
1002 
1003   ShenandoahCollectionSet* set = collection_set();
1004   ShenandoahHeapRegion* r;
1005   set->clear_current_index();
1006   while ((r = set->next()) != nullptr) {
1007     r->make_trash();
1008   }
1009   collection_set()->clear();
1010 }
1011 
1012 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
1013   st->print_cr("Heap Regions:");
1014   st->print_cr("Region state: EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HP=pinned humongous start");
1015   st->print_cr("              HC=humongous continuation, CS=collection set, TR=trash, P=pinned, CSP=pinned collection set");
1016   st->print_cr("BTE=bottom/top/end, TAMS=top-at-mark-start");
1017   st->print_cr("UWM=update watermark, U=used");
1018   st->print_cr("T=TLAB allocs, G=GCLAB allocs");
1019   st->print_cr("S=shared allocs, L=live data");
1020   st->print_cr("CP=critical pins");
1021 
1022   for (size_t i = 0; i < num_regions(); i++) {
1023     get_region(i)->print_on(st);
1024   }
1025 }
1026 
1027 void ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
1028   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1029 
1030   oop humongous_obj = cast_to_oop(start->bottom());
1031   size_t size = humongous_obj->size();
1032   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
1033   size_t index = start->index() + required_regions - 1;
1034 
1035   assert(!start->has_live(), "liveness must be zero");
1036 
1037   for(size_t i = 0; i < required_regions; i++) {
1038     // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
1039     // as it expects that every region belongs to a humongous region starting with a humongous start region.
1040     ShenandoahHeapRegion* region = get_region(index --);
1041 
1042     assert(region->is_humongous(), "expect correct humongous start or continuation");
1043     assert(!region->is_cset(), "Humongous region should not be in collection set");
1044 
1045     region->make_trash_immediate();
1046   }
1047 }
1048 
1049 class ShenandoahCheckCleanGCLABClosure : public ThreadClosure {
1050 public:
1051   ShenandoahCheckCleanGCLABClosure() {}
1052   void do_thread(Thread* thread) {
1053     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1054     assert(gclab != nullptr, "GCLAB should be initialized for %s", thread->name());
1055     assert(gclab->words_remaining() == 0, "GCLAB should not need retirement");
1056   }
1057 };
1058 
1059 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1060 private:
1061   bool const _resize;
1062 public:
1063   ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {}
1064   void do_thread(Thread* thread) {
1065     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1066     assert(gclab != nullptr, "GCLAB should be initialized for %s", thread->name());
1067     gclab->retire();
1068     if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1069       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1070     }
1071   }
1072 };
1073 
1074 void ShenandoahHeap::labs_make_parsable() {
1075   assert(UseTLAB, "Only call with UseTLAB");
1076 
1077   ShenandoahRetireGCLABClosure cl(false);
1078 
1079   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1080     ThreadLocalAllocBuffer& tlab = t->tlab();
1081     tlab.make_parsable();
1082     cl.do_thread(t);
1083   }
1084 
1085   workers()->threads_do(&cl);
1086 }
1087 
1088 void ShenandoahHeap::tlabs_retire(bool resize) {
1089   assert(UseTLAB, "Only call with UseTLAB");
1090   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1091 
1092   ThreadLocalAllocStats stats;
1093 
1094   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1095     ThreadLocalAllocBuffer& tlab = t->tlab();
1096     tlab.retire(&stats);
1097     if (resize) {
1098       tlab.resize();
1099     }
1100   }
1101 
1102   stats.publish();
1103 
1104 #ifdef ASSERT
1105   ShenandoahCheckCleanGCLABClosure cl;
1106   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1107     cl.do_thread(t);
1108   }
1109   workers()->threads_do(&cl);
1110 #endif
1111 }
1112 
1113 void ShenandoahHeap::gclabs_retire(bool resize) {
1114   assert(UseTLAB, "Only call with UseTLAB");
1115   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1116 
1117   ShenandoahRetireGCLABClosure cl(resize);
1118   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1119     cl.do_thread(t);
1120   }
1121   workers()->threads_do(&cl);
1122 
1123   if (safepoint_workers() != nullptr) {
1124     safepoint_workers()->threads_do(&cl);
1125   }
1126 }
1127 
1128 // Returns size in bytes
1129 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1130   // Return the max allowed size, and let the allocation path
1131   // figure out the safe size for current allocation.
1132   return ShenandoahHeapRegion::max_tlab_size_bytes();
1133 }
1134 
1135 size_t ShenandoahHeap::max_tlab_size() const {
1136   // Returns size in words
1137   return ShenandoahHeapRegion::max_tlab_size_words();
1138 }
1139 
1140 void ShenandoahHeap::collect(GCCause::Cause cause) {
1141   control_thread()->request_gc(cause);
1142 }
1143 
1144 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1145   //assert(false, "Shouldn't need to do full collections");
1146 }
1147 
1148 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1149   ShenandoahHeapRegion* r = heap_region_containing(addr);
1150   if (r != nullptr) {
1151     return r->block_start(addr);
1152   }
1153   return nullptr;
1154 }
1155 
1156 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1157   ShenandoahHeapRegion* r = heap_region_containing(addr);
1158   return r->block_is_obj(addr);
1159 }
1160 
1161 bool ShenandoahHeap::print_location(outputStream* st, void* addr) const {
1162   return BlockLocationPrinter<ShenandoahHeap>::print_location(st, addr);
1163 }
1164 
1165 void ShenandoahHeap::prepare_for_verify() {
1166   if (SafepointSynchronize::is_at_safepoint() && UseTLAB) {
1167     labs_make_parsable();
1168   }
1169 }
1170 
1171 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1172   tcl->do_thread(_control_thread);
1173   workers()->threads_do(tcl);
1174   if (_safepoint_workers != nullptr) {
1175     _safepoint_workers->threads_do(tcl);
1176   }
1177 }
1178 
1179 void ShenandoahHeap::print_tracing_info() const {
1180   LogTarget(Info, gc, stats) lt;
1181   if (lt.is_enabled()) {
1182     ResourceMark rm;
1183     LogStream ls(lt);
1184 
1185     phase_timings()->print_global_on(&ls);
1186 
1187     ls.cr();
1188     ls.cr();
1189 
1190     shenandoah_policy()->print_gc_stats(&ls);
1191 
1192     ls.cr();
1193     ls.cr();
1194   }
1195 }
1196 
1197 void ShenandoahHeap::verify(VerifyOption vo) {
1198   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1199     if (ShenandoahVerify) {
1200       verifier()->verify_generic(vo);
1201     } else {
1202       // TODO: Consider allocating verification bitmaps on demand,
1203       // and turn this on unconditionally.
1204     }
1205   }
1206 }
1207 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1208   return _free_set->capacity();
1209 }
1210 
1211 class ObjectIterateScanRootClosure : public BasicOopIterateClosure {
1212 private:
1213   MarkBitMap* _bitmap;
1214   ShenandoahScanObjectStack* _oop_stack;
1215   ShenandoahHeap* const _heap;
1216   ShenandoahMarkingContext* const _marking_context;
1217 
1218   template <class T>
1219   void do_oop_work(T* p) {
1220     T o = RawAccess<>::oop_load(p);
1221     if (!CompressedOops::is_null(o)) {
1222       oop obj = CompressedOops::decode_not_null(o);
1223       if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1224         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1225         return;
1226       }
1227       obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj);
1228 
1229       assert(oopDesc::is_oop(obj), "must be a valid oop");
1230       if (!_bitmap->is_marked(obj)) {
1231         _bitmap->mark(obj);
1232         _oop_stack->push(obj);
1233       }
1234     }
1235   }
1236 public:
1237   ObjectIterateScanRootClosure(MarkBitMap* bitmap, ShenandoahScanObjectStack* oop_stack) :
1238     _bitmap(bitmap), _oop_stack(oop_stack), _heap(ShenandoahHeap::heap()),
1239     _marking_context(_heap->marking_context()) {}
1240   void do_oop(oop* p)       { do_oop_work(p); }
1241   void do_oop(narrowOop* p) { do_oop_work(p); }
1242 };
1243 
1244 /*
1245  * This is public API, used in preparation of object_iterate().
1246  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1247  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1248  * control, we call SH::tlabs_retire, SH::gclabs_retire.
1249  */
1250 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1251   // No-op.
1252 }
1253 
1254 /*
1255  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1256  *
1257  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1258  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1259  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1260  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1261  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1262  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1263  * wiped the bitmap in preparation for next marking).
1264  *
1265  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1266  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1267  * is allowed to report dead objects, but is not required to do so.
1268  */
1269 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1270   // Reset bitmap
1271   if (!prepare_aux_bitmap_for_iteration())
1272     return;
1273 
1274   ShenandoahScanObjectStack oop_stack;
1275   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1276   // Seed the stack with root scan
1277   scan_roots_for_iteration(&oop_stack, &oops);
1278 
1279   // Work through the oop stack to traverse heap
1280   while (! oop_stack.is_empty()) {
1281     oop obj = oop_stack.pop();
1282     assert(oopDesc::is_oop(obj), "must be a valid oop");
1283     cl->do_object(obj);
1284     obj->oop_iterate(&oops);
1285   }
1286 
1287   assert(oop_stack.is_empty(), "should be empty");
1288   // Reclaim bitmap
1289   reclaim_aux_bitmap_for_iteration();
1290 }
1291 
1292 bool ShenandoahHeap::prepare_aux_bitmap_for_iteration() {
1293   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1294 
1295   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1296     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1297     return false;
1298   }
1299   // Reset bitmap
1300   _aux_bit_map.clear();
1301   return true;
1302 }
1303 
1304 void ShenandoahHeap::scan_roots_for_iteration(ShenandoahScanObjectStack* oop_stack, ObjectIterateScanRootClosure* oops) {
1305   // Process GC roots according to current GC cycle
1306   // This populates the work stack with initial objects
1307   // It is important to relinquish the associated locks before diving
1308   // into heap dumper
1309   uint n_workers = safepoint_workers() != nullptr ? safepoint_workers()->active_workers() : 1;
1310   ShenandoahHeapIterationRootScanner rp(n_workers);
1311   rp.roots_do(oops);
1312 }
1313 
1314 void ShenandoahHeap::reclaim_aux_bitmap_for_iteration() {
1315   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1316     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1317   }
1318 }
1319 
1320 // Closure for parallelly iterate objects
1321 class ShenandoahObjectIterateParScanClosure : public BasicOopIterateClosure {
1322 private:
1323   MarkBitMap* _bitmap;
1324   ShenandoahObjToScanQueue* _queue;
1325   ShenandoahHeap* const _heap;
1326   ShenandoahMarkingContext* const _marking_context;
1327 
1328   template <class T>
1329   void do_oop_work(T* p) {
1330     T o = RawAccess<>::oop_load(p);
1331     if (!CompressedOops::is_null(o)) {
1332       oop obj = CompressedOops::decode_not_null(o);
1333       if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1334         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1335         return;
1336       }
1337       obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj);
1338 
1339       assert(oopDesc::is_oop(obj), "Must be a valid oop");
1340       if (_bitmap->par_mark(obj)) {
1341         _queue->push(ShenandoahMarkTask(obj));
1342       }
1343     }
1344   }
1345 public:
1346   ShenandoahObjectIterateParScanClosure(MarkBitMap* bitmap, ShenandoahObjToScanQueue* q) :
1347     _bitmap(bitmap), _queue(q), _heap(ShenandoahHeap::heap()),
1348     _marking_context(_heap->marking_context()) {}
1349   void do_oop(oop* p)       { do_oop_work(p); }
1350   void do_oop(narrowOop* p) { do_oop_work(p); }
1351 };
1352 
1353 // Object iterator for parallel heap iteraion.
1354 // The root scanning phase happenes in construction as a preparation of
1355 // parallel marking queues.
1356 // Every worker processes it's own marking queue. work-stealing is used
1357 // to balance workload.
1358 class ShenandoahParallelObjectIterator : public ParallelObjectIteratorImpl {
1359 private:
1360   uint                         _num_workers;
1361   bool                         _init_ready;
1362   MarkBitMap*                  _aux_bit_map;
1363   ShenandoahHeap*              _heap;
1364   ShenandoahScanObjectStack    _roots_stack; // global roots stack
1365   ShenandoahObjToScanQueueSet* _task_queues;
1366 public:
1367   ShenandoahParallelObjectIterator(uint num_workers, MarkBitMap* bitmap) :
1368         _num_workers(num_workers),
1369         _init_ready(false),
1370         _aux_bit_map(bitmap),
1371         _heap(ShenandoahHeap::heap()) {
1372     // Initialize bitmap
1373     _init_ready = _heap->prepare_aux_bitmap_for_iteration();
1374     if (!_init_ready) {
1375       return;
1376     }
1377 
1378     ObjectIterateScanRootClosure oops(_aux_bit_map, &_roots_stack);
1379     _heap->scan_roots_for_iteration(&_roots_stack, &oops);
1380 
1381     _init_ready = prepare_worker_queues();
1382   }
1383 
1384   ~ShenandoahParallelObjectIterator() {
1385     // Reclaim bitmap
1386     _heap->reclaim_aux_bitmap_for_iteration();
1387     // Reclaim queue for workers
1388     if (_task_queues!= nullptr) {
1389       for (uint i = 0; i < _num_workers; ++i) {
1390         ShenandoahObjToScanQueue* q = _task_queues->queue(i);
1391         if (q != nullptr) {
1392           delete q;
1393           _task_queues->register_queue(i, nullptr);
1394         }
1395       }
1396       delete _task_queues;
1397       _task_queues = nullptr;
1398     }
1399   }
1400 
1401   virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
1402     if (_init_ready) {
1403       object_iterate_parallel(cl, worker_id, _task_queues);
1404     }
1405   }
1406 
1407 private:
1408   // Divide global root_stack into worker queues
1409   bool prepare_worker_queues() {
1410     _task_queues = new ShenandoahObjToScanQueueSet((int) _num_workers);
1411     // Initialize queues for every workers
1412     for (uint i = 0; i < _num_workers; ++i) {
1413       ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue();
1414       _task_queues->register_queue(i, task_queue);
1415     }
1416     // Divide roots among the workers. Assume that object referencing distribution
1417     // is related with root kind, use round-robin to make every worker have same chance
1418     // to process every kind of roots
1419     size_t roots_num = _roots_stack.size();
1420     if (roots_num == 0) {
1421       // No work to do
1422       return false;
1423     }
1424 
1425     for (uint j = 0; j < roots_num; j++) {
1426       uint stack_id = j % _num_workers;
1427       oop obj = _roots_stack.pop();
1428       _task_queues->queue(stack_id)->push(ShenandoahMarkTask(obj));
1429     }
1430     return true;
1431   }
1432 
1433   void object_iterate_parallel(ObjectClosure* cl,
1434                                uint worker_id,
1435                                ShenandoahObjToScanQueueSet* queue_set) {
1436     assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1437     assert(queue_set != nullptr, "task queue must not be null");
1438 
1439     ShenandoahObjToScanQueue* q = queue_set->queue(worker_id);
1440     assert(q != nullptr, "object iterate queue must not be null");
1441 
1442     ShenandoahMarkTask t;
1443     ShenandoahObjectIterateParScanClosure oops(_aux_bit_map, q);
1444 
1445     // Work through the queue to traverse heap.
1446     // Steal when there is no task in queue.
1447     while (q->pop(t) || queue_set->steal(worker_id, t)) {
1448       oop obj = t.obj();
1449       assert(oopDesc::is_oop(obj), "must be a valid oop");
1450       cl->do_object(obj);
1451       obj->oop_iterate(&oops);
1452     }
1453     assert(q->is_empty(), "should be empty");
1454   }
1455 };
1456 
1457 ParallelObjectIteratorImpl* ShenandoahHeap::parallel_object_iterator(uint workers) {
1458   return new ShenandoahParallelObjectIterator(workers, &_aux_bit_map);
1459 }
1460 
1461 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
1462 void ShenandoahHeap::keep_alive(oop obj) {
1463   if (is_concurrent_mark_in_progress() && (obj != nullptr)) {
1464     ShenandoahBarrierSet::barrier_set()->enqueue(obj);
1465   }
1466 }
1467 
1468 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1469   for (size_t i = 0; i < num_regions(); i++) {
1470     ShenandoahHeapRegion* current = get_region(i);
1471     blk->heap_region_do(current);
1472   }
1473 }
1474 
1475 class ShenandoahParallelHeapRegionTask : public WorkerTask {
1476 private:
1477   ShenandoahHeap* const _heap;
1478   ShenandoahHeapRegionClosure* const _blk;
1479 
1480   shenandoah_padding(0);
1481   volatile size_t _index;
1482   shenandoah_padding(1);
1483 
1484 public:
1485   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1486           WorkerTask("Shenandoah Parallel Region Operation"),
1487           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1488 
1489   void work(uint worker_id) {
1490     ShenandoahParallelWorkerSession worker_session(worker_id);
1491     size_t stride = ShenandoahParallelRegionStride;
1492 
1493     size_t max = _heap->num_regions();
1494     while (Atomic::load(&_index) < max) {
1495       size_t cur = Atomic::fetch_then_add(&_index, stride, memory_order_relaxed);
1496       size_t start = cur;
1497       size_t end = MIN2(cur + stride, max);
1498       if (start >= max) break;
1499 
1500       for (size_t i = cur; i < end; i++) {
1501         ShenandoahHeapRegion* current = _heap->get_region(i);
1502         _blk->heap_region_do(current);
1503       }
1504     }
1505   }
1506 };
1507 
1508 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1509   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1510   if (num_regions() > ShenandoahParallelRegionStride) {
1511     ShenandoahParallelHeapRegionTask task(blk);
1512     workers()->run_task(&task);
1513   } else {
1514     heap_region_iterate(blk);
1515   }
1516 }
1517 
1518 class ShenandoahInitMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1519 private:
1520   ShenandoahMarkingContext* const _ctx;
1521 public:
1522   ShenandoahInitMarkUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1523 
1524   void heap_region_do(ShenandoahHeapRegion* r) {
1525     assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->index());
1526     if (r->is_active()) {
1527       // Check if region needs updating its TAMS. We have updated it already during concurrent
1528       // reset, so it is very likely we don't need to do another write here.
1529       if (_ctx->top_at_mark_start(r) != r->top()) {
1530         _ctx->capture_top_at_mark_start(r);
1531       }
1532     } else {
1533       assert(_ctx->top_at_mark_start(r) == r->top(),
1534              "Region " SIZE_FORMAT " should already have correct TAMS", r->index());
1535     }
1536   }
1537 
1538   bool is_thread_safe() { return true; }
1539 };
1540 
1541 class ShenandoahRendezvousClosure : public HandshakeClosure {
1542 public:
1543   inline ShenandoahRendezvousClosure() : HandshakeClosure("ShenandoahRendezvous") {}
1544   inline void do_thread(Thread* thread) {}
1545 };
1546 
1547 void ShenandoahHeap::rendezvous_threads() {
1548   ShenandoahRendezvousClosure cl;
1549   Handshake::execute(&cl);
1550 }
1551 
1552 void ShenandoahHeap::recycle_trash() {
1553   free_set()->recycle_trash();
1554 }
1555 
1556 class ShenandoahResetUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1557 private:
1558   ShenandoahMarkingContext* const _ctx;
1559 public:
1560   ShenandoahResetUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1561 
1562   void heap_region_do(ShenandoahHeapRegion* r) {
1563     if (r->is_active()) {
1564       // Reset live data and set TAMS optimistically. We would recheck these under the pause
1565       // anyway to capture any updates that happened since now.
1566       r->clear_live_data();
1567       _ctx->capture_top_at_mark_start(r);
1568     }
1569   }
1570 
1571   bool is_thread_safe() { return true; }
1572 };
1573 
1574 void ShenandoahHeap::prepare_gc() {
1575   reset_mark_bitmap();
1576 
1577   ShenandoahResetUpdateRegionStateClosure cl;
1578   parallel_heap_region_iterate(&cl);
1579 }
1580 
1581 class ShenandoahFinalMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1582 private:
1583   ShenandoahMarkingContext* const _ctx;
1584   ShenandoahHeapLock* const _lock;
1585 
1586 public:
1587   ShenandoahFinalMarkUpdateRegionStateClosure() :
1588     _ctx(ShenandoahHeap::heap()->complete_marking_context()), _lock(ShenandoahHeap::heap()->lock()) {}
1589 
1590   void heap_region_do(ShenandoahHeapRegion* r) {
1591     if (r->is_active()) {
1592       // All allocations past TAMS are implicitly live, adjust the region data.
1593       // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1594       HeapWord *tams = _ctx->top_at_mark_start(r);
1595       HeapWord *top = r->top();
1596       if (top > tams) {
1597         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1598       }
1599 
1600       // We are about to select the collection set, make sure it knows about
1601       // current pinning status. Also, this allows trashing more regions that
1602       // now have their pinning status dropped.
1603       if (r->is_pinned()) {
1604         if (r->pin_count() == 0) {
1605           ShenandoahHeapLocker locker(_lock);
1606           r->make_unpinned();
1607         }
1608       } else {
1609         if (r->pin_count() > 0) {
1610           ShenandoahHeapLocker locker(_lock);
1611           r->make_pinned();
1612         }
1613       }
1614 
1615       // Remember limit for updating refs. It's guaranteed that we get no
1616       // from-space-refs written from here on.
1617       r->set_update_watermark_at_safepoint(r->top());
1618     } else {
1619       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->index());
1620       assert(_ctx->top_at_mark_start(r) == r->top(),
1621              "Region " SIZE_FORMAT " should have correct TAMS", r->index());
1622     }
1623   }
1624 
1625   bool is_thread_safe() { return true; }
1626 };
1627 
1628 void ShenandoahHeap::prepare_regions_and_collection_set(bool concurrent) {
1629   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
1630   {
1631     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_update_region_states :
1632                                          ShenandoahPhaseTimings::degen_gc_final_update_region_states);
1633     ShenandoahFinalMarkUpdateRegionStateClosure cl;
1634     parallel_heap_region_iterate(&cl);
1635 
1636     assert_pinned_region_status();
1637   }
1638 
1639   {
1640     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::choose_cset :
1641                                          ShenandoahPhaseTimings::degen_gc_choose_cset);
1642     ShenandoahHeapLocker locker(lock());
1643     _collection_set->clear();
1644     heuristics()->choose_collection_set(_collection_set);
1645   }
1646 
1647   {
1648     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_rebuild_freeset :
1649                                          ShenandoahPhaseTimings::degen_gc_final_rebuild_freeset);
1650     ShenandoahHeapLocker locker(lock());
1651     _free_set->rebuild();
1652   }
1653 }
1654 
1655 void ShenandoahHeap::do_class_unloading() {
1656   _unloader.unload();
1657 }
1658 
1659 void ShenandoahHeap::stw_weak_refs(bool full_gc) {
1660   // Weak refs processing
1661   ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs
1662                                                 : ShenandoahPhaseTimings::degen_gc_weakrefs;
1663   ShenandoahTimingsTracker t(phase);
1664   ShenandoahGCWorkerPhase worker_phase(phase);
1665   ref_processor()->process_references(phase, workers(), false /* concurrent */);
1666 }
1667 
1668 void ShenandoahHeap::prepare_update_heap_references(bool concurrent) {
1669   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
1670 
1671   // Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to
1672   // make them parsable for update code to work correctly. Plus, we can compute new sizes
1673   // for future GCLABs here.
1674   if (UseTLAB) {
1675     ShenandoahGCPhase phase(concurrent ?
1676                             ShenandoahPhaseTimings::init_update_refs_manage_gclabs :
1677                             ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs);
1678     gclabs_retire(ResizeTLAB);
1679   }
1680 
1681   _update_refs_iterator.reset();
1682 }
1683 
1684 void ShenandoahHeap::set_gc_state_all_threads(char state) {
1685   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1686     ShenandoahThreadLocalData::set_gc_state(t, state);
1687   }
1688 }
1689 
1690 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1691   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1692   _gc_state.set_cond(mask, value);
1693   set_gc_state_all_threads(_gc_state.raw_value());
1694 }
1695 
1696 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1697   assert(!has_forwarded_objects(), "Not expected before/after mark phase");
1698   set_gc_state_mask(MARKING, in_progress);
1699   ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1700 }
1701 
1702 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1703   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1704   set_gc_state_mask(EVACUATION, in_progress);
1705 }
1706 
1707 void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) {
1708   if (in_progress) {
1709     _concurrent_strong_root_in_progress.set();
1710   } else {
1711     _concurrent_strong_root_in_progress.unset();
1712   }
1713 }
1714 
1715 void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) {
1716   set_gc_state_mask(WEAK_ROOTS, cond);
1717 }
1718 
1719 GCTracer* ShenandoahHeap::tracer() {
1720   return shenandoah_policy()->tracer();
1721 }
1722 
1723 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1724   return _free_set->used();
1725 }
1726 
1727 bool ShenandoahHeap::try_cancel_gc() {
1728   jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
1729   return prev == CANCELLABLE;
1730 }
1731 
1732 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1733   if (try_cancel_gc()) {
1734     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1735     log_info(gc)("%s", msg.buffer());
1736     Events::log(Thread::current(), "%s", msg.buffer());
1737   }
1738 }
1739 
1740 uint ShenandoahHeap::max_workers() {
1741   return _max_workers;
1742 }
1743 
1744 void ShenandoahHeap::stop() {
1745   // The shutdown sequence should be able to terminate when GC is running.
1746 
1747   // Step 0. Notify policy to disable event recording.
1748   _shenandoah_policy->record_shutdown();
1749 
1750   // Step 1. Notify control thread that we are in shutdown.
1751   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1752   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1753   control_thread()->prepare_for_graceful_shutdown();
1754 
1755   // Step 2. Notify GC workers that we are cancelling GC.
1756   cancel_gc(GCCause::_shenandoah_stop_vm);
1757 
1758   // Step 3. Wait until GC worker exits normally.
1759   control_thread()->stop();
1760 }
1761 
1762 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
1763   if (!unload_classes()) return;
1764   // Unload classes and purge SystemDictionary.
1765   {
1766     ShenandoahPhaseTimings::Phase phase = full_gc ?
1767                                           ShenandoahPhaseTimings::full_gc_purge_class_unload :
1768                                           ShenandoahPhaseTimings::degen_gc_purge_class_unload;
1769     ShenandoahIsAliveSelector is_alive;
1770     CodeCache::UnloadingScope scope(is_alive.is_alive_closure());
1771     ShenandoahGCPhase gc_phase(phase);
1772     ShenandoahGCWorkerPhase worker_phase(phase);
1773     bool purged_class = SystemDictionary::do_unloading(gc_timer());
1774 
1775     uint num_workers = _workers->active_workers();
1776     ShenandoahClassUnloadingTask unlink_task(phase, num_workers, purged_class);
1777     _workers->run_task(&unlink_task);
1778   }
1779 
1780   {
1781     ShenandoahGCPhase phase(full_gc ?
1782                             ShenandoahPhaseTimings::full_gc_purge_cldg :
1783                             ShenandoahPhaseTimings::degen_gc_purge_cldg);
1784     ClassLoaderDataGraph::purge(/*at_safepoint*/true);
1785   }
1786   // Resize and verify metaspace
1787   MetaspaceGC::compute_new_size();
1788   DEBUG_ONLY(MetaspaceUtils::verify();)
1789 }
1790 
1791 // Weak roots are either pre-evacuated (final mark) or updated (final updaterefs),
1792 // so they should not have forwarded oops.
1793 // However, we do need to "null" dead oops in the roots, if can not be done
1794 // in concurrent cycles.
1795 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
1796   uint num_workers = _workers->active_workers();
1797   ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
1798                                                ShenandoahPhaseTimings::full_gc_purge_weak_par :
1799                                                ShenandoahPhaseTimings::degen_gc_purge_weak_par;
1800   ShenandoahGCPhase phase(timing_phase);
1801   ShenandoahGCWorkerPhase worker_phase(timing_phase);
1802   // Cleanup weak roots
1803   if (has_forwarded_objects()) {
1804     ShenandoahForwardedIsAliveClosure is_alive;
1805     ShenandoahUpdateRefsClosure keep_alive;
1806     ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure>
1807       cleaning_task(timing_phase, &is_alive, &keep_alive, num_workers);
1808     _workers->run_task(&cleaning_task);
1809   } else {
1810     ShenandoahIsAliveClosure is_alive;
1811 #ifdef ASSERT
1812     ShenandoahAssertNotForwardedClosure verify_cl;
1813     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
1814       cleaning_task(timing_phase, &is_alive, &verify_cl, num_workers);
1815 #else
1816     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
1817       cleaning_task(timing_phase, &is_alive, &do_nothing_cl, num_workers);
1818 #endif
1819     _workers->run_task(&cleaning_task);
1820   }
1821 }
1822 
1823 void ShenandoahHeap::parallel_cleaning(bool full_gc) {
1824   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
1825   assert(is_stw_gc_in_progress(), "Only for Degenerated and Full GC");
1826   ShenandoahGCPhase phase(full_gc ?
1827                           ShenandoahPhaseTimings::full_gc_purge :
1828                           ShenandoahPhaseTimings::degen_gc_purge);
1829   stw_weak_refs(full_gc);
1830   stw_process_weak_roots(full_gc);
1831   stw_unload_classes(full_gc);
1832 }
1833 
1834 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
1835   set_gc_state_mask(HAS_FORWARDED, cond);
1836 }
1837 
1838 void ShenandoahHeap::set_unload_classes(bool uc) {
1839   _unload_classes.set_cond(uc);
1840 }
1841 
1842 bool ShenandoahHeap::unload_classes() const {
1843   return _unload_classes.is_set();
1844 }
1845 
1846 address ShenandoahHeap::in_cset_fast_test_addr() {
1847   ShenandoahHeap* heap = ShenandoahHeap::heap();
1848   assert(heap->collection_set() != nullptr, "Sanity");
1849   return (address) heap->collection_set()->biased_map_address();
1850 }
1851 
1852 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
1853   return Atomic::load(&_bytes_allocated_since_gc_start);
1854 }
1855 
1856 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
1857   Atomic::store(&_bytes_allocated_since_gc_start, (size_t)0);
1858 }
1859 
1860 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
1861   _degenerated_gc_in_progress.set_cond(in_progress);
1862 }
1863 
1864 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
1865   _full_gc_in_progress.set_cond(in_progress);
1866 }
1867 
1868 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
1869   assert (is_full_gc_in_progress(), "should be");
1870   _full_gc_move_in_progress.set_cond(in_progress);
1871 }
1872 
1873 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
1874   set_gc_state_mask(UPDATEREFS, in_progress);
1875 }
1876 
1877 void ShenandoahHeap::register_nmethod(nmethod* nm) {
1878   ShenandoahCodeRoots::register_nmethod(nm);
1879 }
1880 
1881 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
1882   ShenandoahCodeRoots::unregister_nmethod(nm);
1883 }
1884 
1885 void ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
1886   heap_region_containing(o)->record_pin();
1887 }
1888 
1889 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
1890   ShenandoahHeapRegion* r = heap_region_containing(o);
1891   assert(r != nullptr, "Sanity");
1892   assert(r->pin_count() > 0, "Region " SIZE_FORMAT " should have non-zero pins", r->index());
1893   r->record_unpin();
1894 }
1895 
1896 void ShenandoahHeap::sync_pinned_region_status() {
1897   ShenandoahHeapLocker locker(lock());
1898 
1899   for (size_t i = 0; i < num_regions(); i++) {
1900     ShenandoahHeapRegion *r = get_region(i);
1901     if (r->is_active()) {
1902       if (r->is_pinned()) {
1903         if (r->pin_count() == 0) {
1904           r->make_unpinned();
1905         }
1906       } else {
1907         if (r->pin_count() > 0) {
1908           r->make_pinned();
1909         }
1910       }
1911     }
1912   }
1913 
1914   assert_pinned_region_status();
1915 }
1916 
1917 #ifdef ASSERT
1918 void ShenandoahHeap::assert_pinned_region_status() {
1919   for (size_t i = 0; i < num_regions(); i++) {
1920     ShenandoahHeapRegion* r = get_region(i);
1921     assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
1922            "Region " SIZE_FORMAT " pinning status is inconsistent", i);
1923   }
1924 }
1925 #endif
1926 
1927 ConcurrentGCTimer* ShenandoahHeap::gc_timer() const {
1928   return _gc_timer;
1929 }
1930 
1931 void ShenandoahHeap::prepare_concurrent_roots() {
1932   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
1933   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
1934   set_concurrent_strong_root_in_progress(!collection_set()->is_empty());
1935   set_concurrent_weak_root_in_progress(true);
1936   if (unload_classes()) {
1937     _unloader.prepare();
1938   }
1939 }
1940 
1941 void ShenandoahHeap::finish_concurrent_roots() {
1942   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
1943   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
1944   if (unload_classes()) {
1945     _unloader.finish();
1946   }
1947 }
1948 
1949 #ifdef ASSERT
1950 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
1951   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
1952 
1953   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1954     if (UseDynamicNumberOfGCThreads) {
1955       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
1956     } else {
1957       // Use ParallelGCThreads inside safepoints
1958       assert(nworkers == ParallelGCThreads, "Use ParallelGCThreads within safepoints");
1959     }
1960   } else {
1961     if (UseDynamicNumberOfGCThreads) {
1962       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
1963     } else {
1964       // Use ConcGCThreads outside safepoints
1965       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
1966     }
1967   }
1968 }
1969 #endif
1970 
1971 ShenandoahVerifier* ShenandoahHeap::verifier() {
1972   guarantee(ShenandoahVerify, "Should be enabled");
1973   assert (_verifier != nullptr, "sanity");
1974   return _verifier;
1975 }
1976 
1977 template<bool CONCURRENT>
1978 class ShenandoahUpdateHeapRefsTask : public WorkerTask {
1979 private:
1980   ShenandoahHeap* _heap;
1981   ShenandoahRegionIterator* _regions;
1982 public:
1983   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) :
1984     WorkerTask("Shenandoah Update References"),
1985     _heap(ShenandoahHeap::heap()),
1986     _regions(regions) {
1987   }
1988 
1989   void work(uint worker_id) {
1990     if (CONCURRENT) {
1991       ShenandoahConcurrentWorkerSession worker_session(worker_id);
1992       ShenandoahSuspendibleThreadSetJoiner stsj;
1993       do_work<ShenandoahConcUpdateRefsClosure>();
1994     } else {
1995       ShenandoahParallelWorkerSession worker_session(worker_id);
1996       do_work<ShenandoahSTWUpdateRefsClosure>();
1997     }
1998   }
1999 
2000 private:
2001   template<class T>
2002   void do_work() {
2003     T cl;
2004     ShenandoahHeapRegion* r = _regions->next();
2005     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2006     while (r != nullptr) {
2007       HeapWord* update_watermark = r->get_update_watermark();
2008       assert (update_watermark >= r->bottom(), "sanity");
2009       if (r->is_active() && !r->is_cset()) {
2010         _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2011       }
2012       if (ShenandoahPacing) {
2013         _heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom()));
2014       }
2015       if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
2016         return;
2017       }
2018       r = _regions->next();
2019     }
2020   }
2021 };
2022 
2023 void ShenandoahHeap::update_heap_references(bool concurrent) {
2024   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2025 
2026   if (concurrent) {
2027     ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator);
2028     workers()->run_task(&task);
2029   } else {
2030     ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator);
2031     workers()->run_task(&task);
2032   }
2033 }
2034 
2035 
2036 class ShenandoahFinalUpdateRefsUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
2037 private:
2038   ShenandoahHeapLock* const _lock;
2039 
2040 public:
2041   ShenandoahFinalUpdateRefsUpdateRegionStateClosure() : _lock(ShenandoahHeap::heap()->lock()) {}
2042 
2043   void heap_region_do(ShenandoahHeapRegion* r) {
2044     // Drop unnecessary "pinned" state from regions that does not have CP marks
2045     // anymore, as this would allow trashing them.
2046 
2047     if (r->is_active()) {
2048       if (r->is_pinned()) {
2049         if (r->pin_count() == 0) {
2050           ShenandoahHeapLocker locker(_lock);
2051           r->make_unpinned();
2052         }
2053       } else {
2054         if (r->pin_count() > 0) {
2055           ShenandoahHeapLocker locker(_lock);
2056           r->make_pinned();
2057         }
2058       }
2059     }
2060   }
2061 
2062   bool is_thread_safe() { return true; }
2063 };
2064 
2065 void ShenandoahHeap::update_heap_region_states(bool concurrent) {
2066   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2067   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2068 
2069   {
2070     ShenandoahGCPhase phase(concurrent ?
2071                             ShenandoahPhaseTimings::final_update_refs_update_region_states :
2072                             ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states);
2073     ShenandoahFinalUpdateRefsUpdateRegionStateClosure cl;
2074     parallel_heap_region_iterate(&cl);
2075 
2076     assert_pinned_region_status();
2077   }
2078 
2079   {
2080     ShenandoahGCPhase phase(concurrent ?
2081                             ShenandoahPhaseTimings::final_update_refs_trash_cset :
2082                             ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset);
2083     trash_cset_regions();
2084   }
2085 }
2086 
2087 void ShenandoahHeap::rebuild_free_set(bool concurrent) {
2088   {
2089     ShenandoahGCPhase phase(concurrent ?
2090                             ShenandoahPhaseTimings::final_update_refs_rebuild_freeset :
2091                             ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset);
2092     ShenandoahHeapLocker locker(lock());
2093     _free_set->rebuild();
2094   }
2095 }
2096 
2097 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2098   print_on(st);
2099   st->cr();
2100   print_heap_regions_on(st);
2101 }
2102 
2103 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2104   size_t slice = r->index() / _bitmap_regions_per_slice;
2105 
2106   size_t regions_from = _bitmap_regions_per_slice * slice;
2107   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2108   for (size_t g = regions_from; g < regions_to; g++) {
2109     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2110     if (skip_self && g == r->index()) continue;
2111     if (get_region(g)->is_committed()) {
2112       return true;
2113     }
2114   }
2115   return false;
2116 }
2117 
2118 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2119   shenandoah_assert_heaplocked();
2120 
2121   // Bitmaps in special regions do not need commits
2122   if (_bitmap_region_special) {
2123     return true;
2124   }
2125 
2126   if (is_bitmap_slice_committed(r, true)) {
2127     // Some other region from the group is already committed, meaning the bitmap
2128     // slice is already committed, we exit right away.
2129     return true;
2130   }
2131 
2132   // Commit the bitmap slice:
2133   size_t slice = r->index() / _bitmap_regions_per_slice;
2134   size_t off = _bitmap_bytes_per_slice * slice;
2135   size_t len = _bitmap_bytes_per_slice;
2136   char* start = (char*) _bitmap_region.start() + off;
2137 
2138   if (!os::commit_memory(start, len, false)) {
2139     return false;
2140   }
2141 
2142   if (AlwaysPreTouch) {
2143     os::pretouch_memory(start, start + len, _pretouch_bitmap_page_size);
2144   }
2145 
2146   return true;
2147 }
2148 
2149 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2150   shenandoah_assert_heaplocked();
2151 
2152   // Bitmaps in special regions do not need uncommits
2153   if (_bitmap_region_special) {
2154     return true;
2155   }
2156 
2157   if (is_bitmap_slice_committed(r, true)) {
2158     // Some other region from the group is still committed, meaning the bitmap
2159     // slice is should stay committed, exit right away.
2160     return true;
2161   }
2162 
2163   // Uncommit the bitmap slice:
2164   size_t slice = r->index() / _bitmap_regions_per_slice;
2165   size_t off = _bitmap_bytes_per_slice * slice;
2166   size_t len = _bitmap_bytes_per_slice;
2167   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2168     return false;
2169   }
2170   return true;
2171 }
2172 
2173 void ShenandoahHeap::safepoint_synchronize_begin() {
2174   SuspendibleThreadSet::synchronize();
2175 }
2176 
2177 void ShenandoahHeap::safepoint_synchronize_end() {
2178   SuspendibleThreadSet::desynchronize();
2179 }
2180 
2181 void ShenandoahHeap::entry_uncommit(double shrink_before, size_t shrink_until) {
2182   static const char *msg = "Concurrent uncommit";
2183   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_uncommit, true /* log_heap_usage */);
2184   EventMark em("%s", msg);
2185 
2186   op_uncommit(shrink_before, shrink_until);
2187 }
2188 
2189 void ShenandoahHeap::try_inject_alloc_failure() {
2190   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2191     _inject_alloc_failure.set();
2192     os::naked_short_sleep(1);
2193     if (cancelled_gc()) {
2194       log_info(gc)("Allocation failure was successfully injected");
2195     }
2196   }
2197 }
2198 
2199 bool ShenandoahHeap::should_inject_alloc_failure() {
2200   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2201 }
2202 
2203 void ShenandoahHeap::initialize_serviceability() {
2204   _memory_pool = new ShenandoahMemoryPool(this);
2205   _cycle_memory_manager.add_pool(_memory_pool);
2206   _stw_memory_manager.add_pool(_memory_pool);
2207 }
2208 
2209 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2210   GrowableArray<GCMemoryManager*> memory_managers(2);
2211   memory_managers.append(&_cycle_memory_manager);
2212   memory_managers.append(&_stw_memory_manager);
2213   return memory_managers;
2214 }
2215 
2216 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2217   GrowableArray<MemoryPool*> memory_pools(1);
2218   memory_pools.append(_memory_pool);
2219   return memory_pools;
2220 }
2221 
2222 MemoryUsage ShenandoahHeap::memory_usage() {
2223   return _memory_pool->get_memory_usage();
2224 }
2225 
2226 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2227   _heap(ShenandoahHeap::heap()),
2228   _index(0) {}
2229 
2230 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2231   _heap(heap),
2232   _index(0) {}
2233 
2234 void ShenandoahRegionIterator::reset() {
2235   _index = 0;
2236 }
2237 
2238 bool ShenandoahRegionIterator::has_next() const {
2239   return _index < _heap->num_regions();
2240 }
2241 
2242 char ShenandoahHeap::gc_state() const {
2243   return _gc_state.raw_value();
2244 }
2245 
2246 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2247 #ifdef ASSERT
2248   assert(_liveness_cache != nullptr, "sanity");
2249   assert(worker_id < _max_workers, "sanity");
2250   for (uint i = 0; i < num_regions(); i++) {
2251     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2252   }
2253 #endif
2254   return _liveness_cache[worker_id];
2255 }
2256 
2257 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2258   assert(worker_id < _max_workers, "sanity");
2259   assert(_liveness_cache != nullptr, "sanity");
2260   ShenandoahLiveData* ld = _liveness_cache[worker_id];
2261   for (uint i = 0; i < num_regions(); i++) {
2262     ShenandoahLiveData live = ld[i];
2263     if (live > 0) {
2264       ShenandoahHeapRegion* r = get_region(i);
2265       r->increase_live_data_gc_words(live);
2266       ld[i] = 0;
2267     }
2268   }
2269 }
2270 
2271 bool ShenandoahHeap::requires_barriers(stackChunkOop obj) const {
2272   if (is_idle()) return false;
2273 
2274   // Objects allocated after marking start are implicitly alive, don't need any barriers during
2275   // marking phase.
2276   if (is_concurrent_mark_in_progress() &&
2277      !marking_context()->allocated_after_mark_start(obj)) {
2278     return true;
2279   }
2280 
2281   // Can not guarantee obj is deeply good.
2282   if (has_forwarded_objects()) {
2283     return true;
2284   }
2285 
2286   return false;
2287 }