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