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