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