1 /*
   2  * Copyright (c) 2013, 2019, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 #include "memory/allocation.hpp"
  26 #include "memory/universe.hpp"
  27 
  28 #include "gc/shared/gcArguments.hpp"
  29 #include "gc/shared/gcTimer.hpp"
  30 #include "gc/shared/gcTraceTime.inline.hpp"
  31 #include "gc/shared/locationPrinter.inline.hpp"
  32 #include "gc/shared/memAllocator.hpp"
  33 #include "gc/shared/plab.hpp"
  34 
  35 #include "gc/shenandoah/shenandoahAllocTracker.hpp"
  36 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  37 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  38 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  39 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  40 #include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp"
  41 #include "gc/shenandoah/shenandoahConcurrentRoots.hpp"
  42 #include "gc/shenandoah/shenandoahControlThread.hpp"
  43 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  44 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  45 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  46 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  47 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  48 #include "gc/shenandoah/shenandoahMarkCompact.hpp"
  49 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  50 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
  51 #include "gc/shenandoah/shenandoahMetrics.hpp"
  52 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  53 #include "gc/shenandoah/shenandoahNormalMode.hpp"
  54 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  55 #include "gc/shenandoah/shenandoahPacer.inline.hpp"
  56 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
  57 #include "gc/shenandoah/shenandoahPassiveMode.hpp"
  58 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  59 #include "gc/shenandoah/shenandoahStringDedup.hpp"
  60 #include "gc/shenandoah/shenandoahTaskqueue.hpp"
  61 #include "gc/shenandoah/shenandoahTraversalMode.hpp"
  62 #include "gc/shenandoah/shenandoahUtils.hpp"
  63 #include "gc/shenandoah/shenandoahVerifier.hpp"
  64 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
  65 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  66 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  67 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  68 #if INCLUDE_JFR
  69 #include "gc/shenandoah/shenandoahJfrSupport.hpp"
  70 #endif
  71 
  72 #include "memory/metaspace.hpp"
  73 #include "oops/compressedOops.inline.hpp"
  74 #include "runtime/atomic.hpp"
  75 #include "runtime/globals.hpp"
  76 #include "runtime/interfaceSupport.inline.hpp"
  77 #include "runtime/orderAccess.hpp"
  78 #include "runtime/safepointMechanism.hpp"
  79 #include "runtime/vmThread.hpp"
  80 #include "services/mallocTracker.hpp"
  81 
  82 #ifdef ASSERT
  83 template <class T>
  84 void ShenandoahAssertToSpaceClosure::do_oop_work(T* p) {
  85   T o = RawAccess<>::oop_load(p);
  86   if (! CompressedOops::is_null(o)) {
  87     oop obj = CompressedOops::decode_not_null(o);
  88     shenandoah_assert_not_forwarded(p, obj);
  89   }
  90 }
  91 
  92 void ShenandoahAssertToSpaceClosure::do_oop(narrowOop* p) { do_oop_work(p); }
  93 void ShenandoahAssertToSpaceClosure::do_oop(oop* p)       { do_oop_work(p); }
  94 #endif
  95 
  96 class ShenandoahPretouchHeapTask : public AbstractGangTask {
  97 private:
  98   ShenandoahRegionIterator _regions;
  99   const size_t _page_size;
 100 public:
 101   ShenandoahPretouchHeapTask(size_t page_size) :
 102     AbstractGangTask("Shenandoah Pretouch Heap"),
 103     _page_size(page_size) {}
 104 
 105   virtual void work(uint worker_id) {
 106     ShenandoahHeapRegion* r = _regions.next();
 107     while (r != NULL) {
 108       os::pretouch_memory(r->bottom(), r->end(), _page_size);
 109       r = _regions.next();
 110     }
 111   }
 112 };
 113 
 114 class ShenandoahPretouchBitmapTask : public AbstractGangTask {
 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     AbstractGangTask("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->region_number()       * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 131       size_t end   = (r->region_number() + 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       os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
 135 
 136       r = _regions.next();
 137     }
 138   }
 139 };
 140 
 141 jint ShenandoahHeap::initialize() {
 142   initialize_heuristics();
 143 
 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   if (ShenandoahAlwaysPreTouch) {
 156     // Enabled pre-touch means the entire heap is committed right away.
 157     init_byte_size = max_byte_size;
 158   }
 159 
 160   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
 161   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
 162 
 163   _num_regions = ShenandoahHeapRegion::region_count();
 164 
 165   size_t num_committed_regions = init_byte_size / reg_size_bytes;
 166   num_committed_regions = MIN2(num_committed_regions, _num_regions);
 167   assert(num_committed_regions <= _num_regions, "sanity");
 168   _initial_size = num_committed_regions * reg_size_bytes;
 169 
 170   size_t num_min_regions = min_byte_size / reg_size_bytes;
 171   num_min_regions = MIN2(num_min_regions, _num_regions);
 172   assert(num_min_regions <= _num_regions, "sanity");
 173   _minimum_size = num_min_regions * reg_size_bytes;
 174 
 175   _committed = _initial_size;
 176 
 177   size_t heap_page_size   = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 178   size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 179 
 180   //
 181   // Reserve and commit memory for heap
 182   //
 183 
 184   ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
 185   initialize_reserved_region(heap_rs);
 186   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
 187   _heap_region_special = heap_rs.special();
 188 
 189   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 190          "Misaligned heap: " PTR_FORMAT, p2i(base()));
 191 
 192 #if SHENANDOAH_OPTIMIZED_OBJTASK
 193   // The optimized ObjArrayChunkedTask takes some bits away from the full object bits.
 194   // Fail if we ever attempt to address more than we can.
 195   if ((uintptr_t)heap_rs.end() >= ObjArrayChunkedTask::max_addressable()) {
 196     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
 197                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
 198                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
 199                 p2i(heap_rs.base()), p2i(heap_rs.end()), ObjArrayChunkedTask::max_addressable());
 200     vm_exit_during_initialization("Fatal Error", buf);
 201   }
 202 #endif
 203 
 204   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
 205   if (!_heap_region_special) {
 206     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
 207                               "Cannot commit heap memory");
 208   }
 209 
 210   //
 211   // Reserve and commit memory for bitmap(s)
 212   //
 213 
 214   _bitmap_size = MarkBitMap::compute_size(heap_rs.size());
 215   _bitmap_size = align_up(_bitmap_size, bitmap_page_size);
 216 
 217   size_t bitmap_bytes_per_region = reg_size_bytes / MarkBitMap::heap_map_factor();
 218 
 219   guarantee(bitmap_bytes_per_region != 0,
 220             "Bitmap bytes per region should not be zero");
 221   guarantee(is_power_of_2(bitmap_bytes_per_region),
 222             "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
 223 
 224   if (bitmap_page_size > bitmap_bytes_per_region) {
 225     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
 226     _bitmap_bytes_per_slice = bitmap_page_size;
 227   } else {
 228     _bitmap_regions_per_slice = 1;
 229     _bitmap_bytes_per_slice = bitmap_bytes_per_region;
 230   }
 231 
 232   guarantee(_bitmap_regions_per_slice >= 1,
 233             "Should have at least one region per slice: " SIZE_FORMAT,
 234             _bitmap_regions_per_slice);
 235 
 236   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
 237             "Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
 238             _bitmap_bytes_per_slice, bitmap_page_size);
 239 
 240   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
 241   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
 242   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 243   _bitmap_region_special = bitmap.special();
 244 
 245   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
 246                               align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
 247   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
 248   if (!_bitmap_region_special) {
 249     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
 250                               "Cannot commit bitmap memory");
 251   }
 252 
 253   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions);
 254 
 255   if (ShenandoahVerify) {
 256     ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
 257     if (!verify_bitmap.special()) {
 258       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
 259                                 "Cannot commit verification bitmap memory");
 260     }
 261     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 262     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 263     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 264     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 265   }
 266 
 267   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 268   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
 269   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
 270   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 271   _aux_bitmap_region_special = aux_bitmap.special();
 272   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 273 
 274   //
 275   // Create regions and region sets
 276   //
 277 
 278   _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
 279   _free_set = new ShenandoahFreeSet(this, _num_regions);
 280   _collection_set = new ShenandoahCollectionSet(this, sh_rs.base(), sh_rs.size());
 281 
 282   {
 283     ShenandoahHeapLocker locker(lock());
 284 
 285     size_t size_words = ShenandoahHeapRegion::region_size_words();
 286 
 287     for (size_t i = 0; i < _num_regions; i++) {
 288       HeapWord* start = (HeapWord*)sh_rs.base() + size_words * i;
 289       bool is_committed = i < num_committed_regions;
 290       ShenandoahHeapRegion* r = new ShenandoahHeapRegion(this, start, size_words, i, is_committed);
 291 
 292       _marking_context->initialize_top_at_mark_start(r);
 293       _regions[i] = r;
 294       assert(!collection_set()->is_in(i), "New region should not be in collection set");
 295     }
 296 
 297     // Initialize to complete
 298     _marking_context->mark_complete();
 299 
 300     _free_set->rebuild();
 301   }
 302 
 303   if (ShenandoahAlwaysPreTouch) {
 304     assert(!AlwaysPreTouch, "Should have been overridden");
 305 
 306     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
 307     // before initialize() below zeroes it with initializing thread. For any given region,
 308     // we touch the region and the corresponding bitmaps from the same thread.
 309     ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
 310 
 311     size_t pretouch_heap_page_size = heap_page_size;
 312     size_t pretouch_bitmap_page_size = bitmap_page_size;
 313 
 314 #ifdef LINUX
 315     // UseTransparentHugePages would madvise that backing memory can be coalesced into huge
 316     // pages. But, the kernel needs to know that every small page is used, in order to coalesce
 317     // them into huge one. Therefore, we need to pretouch with smaller pages.
 318     if (UseTransparentHugePages) {
 319       pretouch_heap_page_size = (size_t)os::vm_page_size();
 320       pretouch_bitmap_page_size = (size_t)os::vm_page_size();
 321     }
 322 #endif
 323 
 324     // OS memory managers may want to coalesce back-to-back pages. Make their jobs
 325     // simpler by pre-touching continuous spaces (heap and bitmap) separately.
 326 
 327     log_info(gc, init)("Pretouch bitmap: " SIZE_FORMAT " regions, " SIZE_FORMAT " bytes page",
 328                        _num_regions, pretouch_bitmap_page_size);
 329     ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, pretouch_bitmap_page_size);
 330     _workers->run_task(&bcl);
 331 
 332     log_info(gc, init)("Pretouch heap: " SIZE_FORMAT " regions, " SIZE_FORMAT " bytes page",
 333                        _num_regions, pretouch_heap_page_size);
 334     ShenandoahPretouchHeapTask hcl(pretouch_heap_page_size);
 335     _workers->run_task(&hcl);
 336   }
 337 
 338   //
 339   // Initialize the rest of GC subsystems
 340   //
 341 
 342   _liveness_cache = NEW_C_HEAP_ARRAY(jushort*, _max_workers, mtGC);
 343   for (uint worker = 0; worker < _max_workers; worker++) {
 344     _liveness_cache[worker] = NEW_C_HEAP_ARRAY(jushort, _num_regions, mtGC);
 345     Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(jushort));
 346   }
 347 
 348   // There should probably be Shenandoah-specific options for these,
 349   // just as there are G1-specific options.
 350   {
 351     ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
 352     satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
 353     satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
 354   }
 355 
 356   _monitoring_support = new ShenandoahMonitoringSupport(this);
 357   _phase_timings = new ShenandoahPhaseTimings();
 358   ShenandoahStringDedup::initialize();
 359   ShenandoahCodeRoots::initialize();
 360 
 361   if (ShenandoahAllocationTrace) {
 362     _alloc_tracker = new ShenandoahAllocTracker();
 363   }
 364 
 365   if (ShenandoahPacing) {
 366     _pacer = new ShenandoahPacer(this);
 367     _pacer->setup_for_idle();
 368   } else {
 369     _pacer = NULL;
 370   }
 371 
 372   _traversal_gc = strcmp(ShenandoahGCMode, "traversal") == 0 ?
 373                   new ShenandoahTraversalGC(this, _num_regions) :
 374                   NULL;
 375 
 376   _control_thread = new ShenandoahControlThread();
 377 
 378   log_info(gc, init)("Initialize Shenandoah heap: " SIZE_FORMAT "%s initial, " SIZE_FORMAT "%s min, " SIZE_FORMAT "%s max",
 379                      byte_size_in_proper_unit(_initial_size),  proper_unit_for_byte_size(_initial_size),
 380                      byte_size_in_proper_unit(_minimum_size),  proper_unit_for_byte_size(_minimum_size),
 381                      byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity())
 382   );
 383 
 384   log_info(gc, init)("Safepointing mechanism: %s",
 385                      SafepointMechanism::uses_thread_local_poll() ? "thread-local poll" :
 386                      (SafepointMechanism::uses_global_page_poll() ? "global-page poll" : "unknown"));
 387 
 388   return JNI_OK;
 389 }
 390 
 391 void ShenandoahHeap::initialize_heuristics() {
 392   if (ShenandoahGCMode != NULL) {
 393     if (strcmp(ShenandoahGCMode, "traversal") == 0) {
 394       _gc_mode = new ShenandoahTraversalMode();
 395     } else if (strcmp(ShenandoahGCMode, "normal") == 0) {
 396       _gc_mode = new ShenandoahNormalMode();
 397     } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
 398       _gc_mode = new ShenandoahPassiveMode();
 399     } else {
 400       vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
 401     }
 402   } else {
 403     ShouldNotReachHere();
 404   }
 405   _gc_mode->initialize_flags();
 406   _heuristics = _gc_mode->initialize_heuristics();
 407 
 408   if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 409     vm_exit_during_initialization(
 410             err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 411                     _heuristics->name()));
 412   }
 413   if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {
 414     vm_exit_during_initialization(
 415             err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 416                     _heuristics->name()));
 417   }
 418   log_info(gc, init)("Shenandoah heuristics: %s",
 419                      _heuristics->name());
 420 }
 421 
 422 #ifdef _MSC_VER
 423 #pragma warning( push )
 424 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 425 #endif
 426 
 427 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 428   CollectedHeap(),
 429   _initial_size(0),
 430   _used(0),
 431   _committed(0),
 432   _bytes_allocated_since_gc_start(0),
 433   _max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),
 434   _workers(NULL),
 435   _safepoint_workers(NULL),
 436   _heap_region_special(false),
 437   _num_regions(0),
 438   _regions(NULL),
 439   _update_refs_iterator(this),
 440   _control_thread(NULL),
 441   _shenandoah_policy(policy),
 442   _heuristics(NULL),
 443   _free_set(NULL),
 444   _scm(new ShenandoahConcurrentMark()),
 445   _traversal_gc(NULL),
 446   _full_gc(new ShenandoahMarkCompact()),
 447   _pacer(NULL),
 448   _verifier(NULL),
 449   _alloc_tracker(NULL),
 450   _phase_timings(NULL),
 451   _monitoring_support(NULL),
 452   _memory_pool(NULL),
 453   _stw_memory_manager("Shenandoah Pauses", "end of GC pause"),
 454   _cycle_memory_manager("Shenandoah Cycles", "end of GC cycle"),
 455   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
 456   _soft_ref_policy(),
 457   _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),
 458   _ref_processor(NULL),
 459   _marking_context(NULL),
 460   _bitmap_size(0),
 461   _bitmap_regions_per_slice(0),
 462   _bitmap_bytes_per_slice(0),
 463   _bitmap_region_special(false),
 464   _aux_bitmap_region_special(false),
 465   _liveness_cache(NULL),
 466   _collection_set(NULL)
 467 {
 468   log_info(gc, init)("GC threads: " UINT32_FORMAT " parallel, " UINT32_FORMAT " concurrent", ParallelGCThreads, ConcGCThreads);
 469   log_info(gc, init)("Reference processing: %s", ParallelRefProcEnabled ? "parallel" : "serial");
 470 
 471   BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this));
 472 
 473   _max_workers = MAX2(_max_workers, 1U);
 474   _workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,
 475                             /* are_GC_task_threads */ true,
 476                             /* are_ConcurrentGC_threads */ true);
 477   if (_workers == NULL) {
 478     vm_exit_during_initialization("Failed necessary allocation.");
 479   } else {
 480     _workers->initialize_workers();
 481   }
 482 
 483   if (ShenandoahParallelSafepointThreads > 1) {
 484     _safepoint_workers = new ShenandoahWorkGang("Safepoint Cleanup Thread",
 485                                                 ShenandoahParallelSafepointThreads,
 486                       /* are_GC_task_threads */ false,
 487                  /* are_ConcurrentGC_threads */ false);
 488     _safepoint_workers->initialize_workers();
 489   }
 490 }
 491 
 492 #ifdef _MSC_VER
 493 #pragma warning( pop )
 494 #endif
 495 
 496 class ShenandoahResetBitmapTask : public AbstractGangTask {
 497 private:
 498   ShenandoahRegionIterator _regions;
 499 
 500 public:
 501   ShenandoahResetBitmapTask() :
 502     AbstractGangTask("Parallel Reset Bitmap Task") {}
 503 
 504   void work(uint worker_id) {
 505     ShenandoahHeapRegion* region = _regions.next();
 506     ShenandoahHeap* heap = ShenandoahHeap::heap();
 507     ShenandoahMarkingContext* const ctx = heap->marking_context();
 508     while (region != NULL) {
 509       if (heap->is_bitmap_slice_committed(region)) {
 510         ctx->clear_bitmap(region);
 511       }
 512       region = _regions.next();
 513     }
 514   }
 515 };
 516 
 517 void ShenandoahHeap::reset_mark_bitmap() {
 518   assert_gc_workers(_workers->active_workers());
 519   mark_incomplete_marking_context();
 520 
 521   ShenandoahResetBitmapTask task;
 522   _workers->run_task(&task);
 523 }
 524 
 525 void ShenandoahHeap::print_on(outputStream* st) const {
 526   st->print_cr("Shenandoah Heap");
 527   st->print_cr(" " SIZE_FORMAT "%s total, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",
 528                byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),
 529                byte_size_in_proper_unit(committed()),    proper_unit_for_byte_size(committed()),
 530                byte_size_in_proper_unit(used()),         proper_unit_for_byte_size(used()));
 531   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",
 532                num_regions(),
 533                byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),
 534                proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));
 535 
 536   st->print("Status: ");
 537   if (has_forwarded_objects())               st->print("has forwarded objects, ");
 538   if (is_concurrent_mark_in_progress())      st->print("marking, ");
 539   if (is_evacuation_in_progress())           st->print("evacuating, ");
 540   if (is_update_refs_in_progress())          st->print("updating refs, ");
 541   if (is_concurrent_traversal_in_progress()) st->print("traversal, ");
 542   if (is_degenerated_gc_in_progress())       st->print("degenerated gc, ");
 543   if (is_full_gc_in_progress())              st->print("full gc, ");
 544   if (is_full_gc_move_in_progress())         st->print("full gc move, ");
 545 
 546   if (cancelled_gc()) {
 547     st->print("cancelled");
 548   } else {
 549     st->print("not cancelled");
 550   }
 551   st->cr();
 552 
 553   st->print_cr("Reserved region:");
 554   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
 555                p2i(reserved_region().start()),
 556                p2i(reserved_region().end()));
 557 
 558   ShenandoahCollectionSet* cset = collection_set();
 559   st->print_cr("Collection set:");
 560   if (cset != NULL) {
 561     st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));
 562     st->print_cr(" - map (biased):  " PTR_FORMAT, p2i(cset->biased_map_address()));
 563   } else {
 564     st->print_cr(" (NULL)");
 565   }
 566 
 567   st->cr();
 568   MetaspaceUtils::print_on(st);
 569 
 570   if (Verbose) {
 571     print_heap_regions_on(st);
 572   }
 573 }
 574 
 575 class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {
 576 public:
 577   void do_thread(Thread* thread) {
 578     assert(thread != NULL, "Sanity");
 579     assert(thread->is_Worker_thread(), "Only worker thread expected");
 580     ShenandoahThreadLocalData::initialize_gclab(thread);
 581   }
 582 };
 583 
 584 void ShenandoahHeap::post_initialize() {
 585   CollectedHeap::post_initialize();
 586   MutexLocker ml(Threads_lock);
 587 
 588   ShenandoahInitWorkerGCLABClosure init_gclabs;
 589   _workers->threads_do(&init_gclabs);
 590 
 591   // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 592   // Now, we will let WorkGang to initialize gclab when new worker is created.
 593   _workers->set_initialize_gclab();
 594 
 595   _scm->initialize(_max_workers);
 596   _full_gc->initialize(_gc_timer);
 597 
 598   ref_processing_init();
 599 
 600   _heuristics->initialize();
 601 
 602   JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers());
 603 }
 604 
 605 size_t ShenandoahHeap::used() const {
 606   return Atomic::load_acquire(&_used);
 607 }
 608 
 609 size_t ShenandoahHeap::committed() const {
 610   OrderAccess::acquire();
 611   return _committed;
 612 }
 613 
 614 void ShenandoahHeap::increase_committed(size_t bytes) {
 615   assert_heaplock_or_safepoint();
 616   _committed += bytes;
 617 }
 618 
 619 void ShenandoahHeap::decrease_committed(size_t bytes) {
 620   assert_heaplock_or_safepoint();
 621   _committed -= bytes;
 622 }
 623 
 624 void ShenandoahHeap::increase_used(size_t bytes) {
 625   Atomic::add(&_used, bytes);
 626 }
 627 
 628 void ShenandoahHeap::set_used(size_t bytes) {
 629   Atomic::release_store_fence(&_used, bytes);
 630 }
 631 
 632 void ShenandoahHeap::decrease_used(size_t bytes) {
 633   assert(used() >= bytes, "never decrease heap size by more than we've left");
 634   Atomic::sub(&_used, bytes);
 635 }
 636 
 637 void ShenandoahHeap::increase_allocated(size_t bytes) {
 638   Atomic::add(&_bytes_allocated_since_gc_start, bytes);
 639 }
 640 
 641 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
 642   size_t bytes = words * HeapWordSize;
 643   if (!waste) {
 644     increase_used(bytes);
 645   }
 646   increase_allocated(bytes);
 647   if (ShenandoahPacing) {
 648     control_thread()->pacing_notify_alloc(words);
 649     if (waste) {
 650       pacer()->claim_for_alloc(words, true);
 651     }
 652   }
 653 }
 654 
 655 size_t ShenandoahHeap::capacity() const {
 656   return committed();
 657 }
 658 
 659 size_t ShenandoahHeap::max_capacity() const {
 660   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 661 }
 662 
 663 size_t ShenandoahHeap::min_capacity() const {
 664   return _minimum_size;
 665 }
 666 
 667 size_t ShenandoahHeap::initial_capacity() const {
 668   return _initial_size;
 669 }
 670 
 671 bool ShenandoahHeap::is_in(const void* p) const {
 672   HeapWord* heap_base = (HeapWord*) base();
 673   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
 674   return p >= heap_base && p < last_region_end;
 675 }
 676 
 677 void ShenandoahHeap::op_uncommit(double shrink_before) {
 678   assert (ShenandoahUncommit, "should be enabled");
 679 
 680   // Application allocates from the beginning of the heap, and GC allocates at
 681   // the end of it. It is more efficient to uncommit from the end, so that applications
 682   // could enjoy the near committed regions. GC allocations are much less frequent,
 683   // and therefore can accept the committing costs.
 684 
 685   size_t count = 0;
 686   for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
 687     ShenandoahHeapRegion* r = get_region(i - 1);
 688     if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
 689       ShenandoahHeapLocker locker(lock());
 690       if (r->is_empty_committed()) {
 691         // Do not uncommit below minimal capacity
 692         if (committed() < min_capacity() + ShenandoahHeapRegion::region_size_bytes()) {
 693           break;
 694         }
 695 
 696         r->make_uncommitted();
 697         count++;
 698       }
 699     }
 700     SpinPause(); // allow allocators to take the lock
 701   }
 702 
 703   if (count > 0) {
 704     control_thread()->notify_heap_changed();
 705   }
 706 }
 707 
 708 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 709   // New object should fit the GCLAB size
 710   size_t min_size = MAX2(size, PLAB::min_size());
 711 
 712   // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
 713   size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
 714   new_size = MIN2(new_size, PLAB::max_size());
 715   new_size = MAX2(new_size, PLAB::min_size());
 716 
 717   // Record new heuristic value even if we take any shortcut. This captures
 718   // the case when moderately-sized objects always take a shortcut. At some point,
 719   // heuristics should catch up with them.
 720   ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
 721 
 722   if (new_size < size) {
 723     // New size still does not fit the object. Fall back to shared allocation.
 724     // This avoids retiring perfectly good GCLABs, when we encounter a large object.
 725     return NULL;
 726   }
 727 
 728   // Retire current GCLAB, and allocate a new one.
 729   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
 730   gclab->retire();
 731 
 732   size_t actual_size = 0;
 733   HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);
 734   if (gclab_buf == NULL) {
 735     return NULL;
 736   }
 737 
 738   assert (size <= actual_size, "allocation should fit");
 739 
 740   if (ZeroTLAB) {
 741     // ..and clear it.
 742     Copy::zero_to_words(gclab_buf, actual_size);
 743   } else {
 744     // ...and zap just allocated object.
 745 #ifdef ASSERT
 746     // Skip mangling the space corresponding to the object header to
 747     // ensure that the returned space is not considered parsable by
 748     // any concurrent GC thread.
 749     size_t hdr_size = oopDesc::header_size();
 750     Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 751 #endif // ASSERT
 752   }
 753   gclab->set_buf(gclab_buf, actual_size);
 754   return gclab->allocate(size);
 755 }
 756 
 757 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
 758                                             size_t requested_size,
 759                                             size_t* actual_size) {
 760   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
 761   HeapWord* res = allocate_memory(req);
 762   if (res != NULL) {
 763     *actual_size = req.actual_size();
 764   } else {
 765     *actual_size = 0;
 766   }
 767   return res;
 768 }
 769 
 770 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
 771                                              size_t word_size,
 772                                              size_t* actual_size) {
 773   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
 774   HeapWord* res = allocate_memory(req);
 775   if (res != NULL) {
 776     *actual_size = req.actual_size();
 777   } else {
 778     *actual_size = 0;
 779   }
 780   return res;
 781 }
 782 
 783 ShenandoahHeap* ShenandoahHeap::heap() {
 784   CollectedHeap* heap = Universe::heap();
 785   assert(heap != NULL, "Unitialized access to ShenandoahHeap::heap()");
 786   assert(heap->kind() == CollectedHeap::Shenandoah, "not a shenandoah heap");
 787   return (ShenandoahHeap*) heap;
 788 }
 789 
 790 ShenandoahHeap* ShenandoahHeap::heap_no_check() {
 791   CollectedHeap* heap = Universe::heap();
 792   return (ShenandoahHeap*) heap;
 793 }
 794 
 795 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {
 796   ShenandoahAllocTrace trace_alloc(req.size(), req.type());
 797 
 798   intptr_t pacer_epoch = 0;
 799   bool in_new_region = false;
 800   HeapWord* result = NULL;
 801 
 802   if (req.is_mutator_alloc()) {
 803     if (ShenandoahPacing) {
 804       pacer()->pace_for_alloc(req.size());
 805       pacer_epoch = pacer()->epoch();
 806     }
 807 
 808     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
 809       result = allocate_memory_under_lock(req, in_new_region);
 810     }
 811 
 812     // Allocation failed, block until control thread reacted, then retry allocation.
 813     //
 814     // It might happen that one of the threads requesting allocation would unblock
 815     // way later after GC happened, only to fail the second allocation, because
 816     // other threads have already depleted the free storage. In this case, a better
 817     // strategy is to try again, as long as GC makes progress.
 818     //
 819     // Then, we need to make sure the allocation was retried after at least one
 820     // Full GC, which means we want to try more than ShenandoahFullGCThreshold times.
 821 
 822     size_t tries = 0;
 823 
 824     while (result == NULL && _progress_last_gc.is_set()) {
 825       tries++;
 826       control_thread()->handle_alloc_failure(req.size());
 827       result = allocate_memory_under_lock(req, in_new_region);
 828     }
 829 
 830     while (result == NULL && tries <= ShenandoahFullGCThreshold) {
 831       tries++;
 832       control_thread()->handle_alloc_failure(req.size());
 833       result = allocate_memory_under_lock(req, in_new_region);
 834     }
 835 
 836   } else {
 837     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
 838     result = allocate_memory_under_lock(req, in_new_region);
 839     // Do not call handle_alloc_failure() here, because we cannot block.
 840     // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
 841   }
 842 
 843   if (in_new_region) {
 844     control_thread()->notify_heap_changed();
 845   }
 846 
 847   if (result != NULL) {
 848     size_t requested = req.size();
 849     size_t actual = req.actual_size();
 850 
 851     assert (req.is_lab_alloc() || (requested == actual),
 852             "Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
 853             ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
 854 
 855     if (req.is_mutator_alloc()) {
 856       notify_mutator_alloc_words(actual, false);
 857 
 858       // If we requested more than we were granted, give the rest back to pacer.
 859       // This only matters if we are in the same pacing epoch: do not try to unpace
 860       // over the budget for the other phase.
 861       if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
 862         pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
 863       }
 864     } else {
 865       increase_used(actual*HeapWordSize);
 866     }
 867   }
 868 
 869   return result;
 870 }
 871 
 872 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {
 873   ShenandoahHeapLocker locker(lock());
 874   return _free_set->allocate(req, in_new_region);
 875 }
 876 
 877 HeapWord* ShenandoahHeap::mem_allocate(size_t size,
 878                                         bool*  gc_overhead_limit_was_exceeded) {
 879   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
 880   return allocate_memory(req);
 881 }
 882 
 883 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
 884                                                              size_t size,
 885                                                              Metaspace::MetadataType mdtype) {
 886   MetaWord* result;
 887 
 888   // Inform metaspace OOM to GC heuristics if class unloading is possible.
 889   if (heuristics()->can_unload_classes()) {
 890     ShenandoahHeuristics* h = heuristics();
 891     h->record_metaspace_oom();
 892   }
 893 
 894   // Expand and retry allocation
 895   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
 896   if (result != NULL) {
 897     return result;
 898   }
 899 
 900   // Start full GC
 901   collect(GCCause::_metadata_GC_clear_soft_refs);
 902 
 903   // Retry allocation
 904   result = loader_data->metaspace_non_null()->allocate(size, mdtype);
 905   if (result != NULL) {
 906     return result;
 907   }
 908 
 909   // Expand and retry allocation
 910   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
 911   if (result != NULL) {
 912     return result;
 913   }
 914 
 915   // Out of memory
 916   return NULL;
 917 }
 918 
 919 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
 920 private:
 921   ShenandoahHeap* const _heap;
 922   Thread* const _thread;
 923 public:
 924   ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
 925     _heap(heap), _thread(Thread::current()) {}
 926 
 927   void do_object(oop p) {
 928     shenandoah_assert_marked(NULL, p);
 929     if (!p->is_forwarded()) {
 930       _heap->evacuate_object(p, _thread);
 931     }
 932   }
 933 };
 934 
 935 class ShenandoahEvacuationTask : public AbstractGangTask {
 936 private:
 937   ShenandoahHeap* const _sh;
 938   ShenandoahCollectionSet* const _cs;
 939   bool _concurrent;
 940 public:
 941   ShenandoahEvacuationTask(ShenandoahHeap* sh,
 942                            ShenandoahCollectionSet* cs,
 943                            bool concurrent) :
 944     AbstractGangTask("Parallel Evacuation Task"),
 945     _sh(sh),
 946     _cs(cs),
 947     _concurrent(concurrent)
 948   {}
 949 
 950   void work(uint worker_id) {
 951     if (_concurrent) {
 952       ShenandoahConcurrentWorkerSession worker_session(worker_id);
 953       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
 954       ShenandoahEvacOOMScope oom_evac_scope;
 955       do_work();
 956     } else {
 957       ShenandoahParallelWorkerSession worker_session(worker_id);
 958       ShenandoahEvacOOMScope oom_evac_scope;
 959       do_work();
 960     }
 961   }
 962 
 963 private:
 964   void do_work() {
 965     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
 966     ShenandoahHeapRegion* r;
 967     while ((r =_cs->claim_next()) != NULL) {
 968       assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->region_number());
 969       _sh->marked_object_iterate(r, &cl);
 970 
 971       if (ShenandoahPacing) {
 972         _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
 973       }
 974 
 975       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
 976         break;
 977       }
 978     }
 979   }
 980 };
 981 
 982 void ShenandoahHeap::trash_cset_regions() {
 983   ShenandoahHeapLocker locker(lock());
 984 
 985   ShenandoahCollectionSet* set = collection_set();
 986   ShenandoahHeapRegion* r;
 987   set->clear_current_index();
 988   while ((r = set->next()) != NULL) {
 989     r->make_trash();
 990   }
 991   collection_set()->clear();
 992 }
 993 
 994 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
 995   st->print_cr("Heap Regions:");
 996   st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");
 997   st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
 998   st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start (previous, next)");
 999   st->print_cr("SN=alloc sequence numbers (first mutator, last mutator, first gc, last gc)");
1000 
1001   for (size_t i = 0; i < num_regions(); i++) {
1002     get_region(i)->print_on(st);
1003   }
1004 }
1005 
1006 void ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
1007   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1008 
1009   oop humongous_obj = oop(start->bottom());
1010   size_t size = humongous_obj->size();
1011   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
1012   size_t index = start->region_number() + required_regions - 1;
1013 
1014   assert(!start->has_live(), "liveness must be zero");
1015 
1016   for(size_t i = 0; i < required_regions; i++) {
1017     // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
1018     // as it expects that every region belongs to a humongous region starting with a humongous start region.
1019     ShenandoahHeapRegion* region = get_region(index --);
1020 
1021     assert(region->is_humongous(), "expect correct humongous start or continuation");
1022     assert(!region->is_cset(), "Humongous region should not be in collection set");
1023 
1024     region->make_trash_immediate();
1025   }
1026 }
1027 
1028 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1029 public:
1030   void do_thread(Thread* thread) {
1031     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1032     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1033     gclab->retire();
1034   }
1035 };
1036 
1037 void ShenandoahHeap::make_parsable(bool retire_tlabs) {
1038   if (UseTLAB) {
1039     CollectedHeap::ensure_parsability(retire_tlabs);
1040   }
1041   ShenandoahRetireGCLABClosure cl;
1042   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1043     cl.do_thread(t);
1044   }
1045   workers()->threads_do(&cl);
1046 }
1047 
1048 void ShenandoahHeap::resize_tlabs() {
1049   CollectedHeap::resize_all_tlabs();
1050 }
1051 
1052 class ShenandoahEvacuateUpdateRootsTask : public AbstractGangTask {
1053 private:
1054   ShenandoahRootEvacuator* _rp;
1055 
1056 public:
1057   ShenandoahEvacuateUpdateRootsTask(ShenandoahRootEvacuator* rp) :
1058     AbstractGangTask("Shenandoah evacuate and update roots"),
1059     _rp(rp) {}
1060 
1061   void work(uint worker_id) {
1062     ShenandoahParallelWorkerSession worker_session(worker_id);
1063     ShenandoahEvacOOMScope oom_evac_scope;
1064     ShenandoahEvacuateUpdateRootsClosure cl;
1065     MarkingCodeBlobClosure blobsCl(&cl, CodeBlobToOopClosure::FixRelocations);
1066     _rp->roots_do(worker_id, &cl);
1067   }
1068 };
1069 
1070 void ShenandoahHeap::evacuate_and_update_roots() {
1071 #if COMPILER2_OR_JVMCI
1072   DerivedPointerTable::clear();
1073 #endif
1074   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only iterate roots while world is stopped");
1075   {
1076     // Include concurrent roots if current cycle can not process those roots concurrently
1077     ShenandoahRootEvacuator rp(workers()->active_workers(),
1078                                ShenandoahPhaseTimings::init_evac,
1079                                !ShenandoahConcurrentRoots::should_do_concurrent_roots());
1080     ShenandoahEvacuateUpdateRootsTask roots_task(&rp);
1081     workers()->run_task(&roots_task);
1082   }
1083 
1084 #if COMPILER2_OR_JVMCI
1085   DerivedPointerTable::update_pointers();
1086 #endif
1087 }
1088 
1089 // Returns size in bytes
1090 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1091   if (ShenandoahElasticTLAB) {
1092     // With Elastic TLABs, return the max allowed size, and let the allocation path
1093     // figure out the safe size for current allocation.
1094     return ShenandoahHeapRegion::max_tlab_size_bytes();
1095   } else {
1096     return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());
1097   }
1098 }
1099 
1100 size_t ShenandoahHeap::max_tlab_size() const {
1101   // Returns size in words
1102   return ShenandoahHeapRegion::max_tlab_size_words();
1103 }
1104 
1105 class ShenandoahRetireAndResetGCLABClosure : public ThreadClosure {
1106 public:
1107   void do_thread(Thread* thread) {
1108     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1109     gclab->retire();
1110     if (ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1111       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1112     }
1113   }
1114 };
1115 
1116 void ShenandoahHeap::retire_and_reset_gclabs() {
1117   ShenandoahRetireAndResetGCLABClosure cl;
1118   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1119     cl.do_thread(t);
1120   }
1121   workers()->threads_do(&cl);
1122 }
1123 
1124 void ShenandoahHeap::collect(GCCause::Cause cause) {
1125   control_thread()->request_gc(cause);
1126 }
1127 
1128 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1129   //assert(false, "Shouldn't need to do full collections");
1130 }
1131 
1132 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1133   Space* sp = heap_region_containing(addr);
1134   if (sp != NULL) {
1135     return sp->block_start(addr);
1136   }
1137   return NULL;
1138 }
1139 
1140 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1141   Space* sp = heap_region_containing(addr);
1142   return sp->block_is_obj(addr);
1143 }
1144 
1145 bool ShenandoahHeap::print_location(outputStream* st, void* addr) const {
1146   return BlockLocationPrinter<ShenandoahHeap>::print_location(st, addr);
1147 }
1148 
1149 jlong ShenandoahHeap::millis_since_last_gc() {
1150   double v = heuristics()->time_since_last_gc() * 1000;
1151   assert(0 <= v && v <= max_jlong, "value should fit: %f", v);
1152   return (jlong)v;
1153 }
1154 
1155 void ShenandoahHeap::prepare_for_verify() {
1156   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
1157     make_parsable(false);
1158   }
1159 }
1160 
1161 void ShenandoahHeap::print_gc_threads_on(outputStream* st) const {
1162   workers()->print_worker_threads_on(st);
1163   if (ShenandoahStringDedup::is_enabled()) {
1164     ShenandoahStringDedup::print_worker_threads_on(st);
1165   }
1166 }
1167 
1168 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1169   workers()->threads_do(tcl);
1170   if (_safepoint_workers != NULL) {
1171     _safepoint_workers->threads_do(tcl);
1172   }
1173   if (ShenandoahStringDedup::is_enabled()) {
1174     ShenandoahStringDedup::threads_do(tcl);
1175   }
1176 }
1177 
1178 void ShenandoahHeap::print_tracing_info() const {
1179   LogTarget(Info, gc, stats) lt;
1180   if (lt.is_enabled()) {
1181     ResourceMark rm;
1182     LogStream ls(lt);
1183 
1184     phase_timings()->print_on(&ls);
1185 
1186     ls.cr();
1187     ls.cr();
1188 
1189     shenandoah_policy()->print_gc_stats(&ls);
1190 
1191     ls.cr();
1192     ls.cr();
1193 
1194     if (ShenandoahPacing) {
1195       pacer()->print_on(&ls);
1196     }
1197 
1198     ls.cr();
1199     ls.cr();
1200 
1201     if (ShenandoahAllocationTrace) {
1202       assert(alloc_tracker() != NULL, "Must be");
1203       alloc_tracker()->print_on(&ls);
1204     } else {
1205       ls.print_cr("  Allocation tracing is disabled, use -XX:+ShenandoahAllocationTrace to enable.");
1206     }
1207   }
1208 }
1209 
1210 void ShenandoahHeap::verify(VerifyOption vo) {
1211   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1212     if (ShenandoahVerify) {
1213       verifier()->verify_generic(vo);
1214     } else {
1215       // TODO: Consider allocating verification bitmaps on demand,
1216       // and turn this on unconditionally.
1217     }
1218   }
1219 }
1220 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1221   return _free_set->capacity();
1222 }
1223 
1224 class ObjectIterateScanRootClosure : public BasicOopIterateClosure {
1225 private:
1226   MarkBitMap* _bitmap;
1227   Stack<oop,mtGC>* _oop_stack;
1228 
1229   template <class T>
1230   void do_oop_work(T* p) {
1231     T o = RawAccess<>::oop_load(p);
1232     if (!CompressedOops::is_null(o)) {
1233       oop obj = CompressedOops::decode_not_null(o);
1234       oop fwd = (oop) ShenandoahForwarding::get_forwardee_raw_unchecked(obj);
1235       if (fwd == NULL) {
1236         // There is an odd interaction with VM_HeapWalkOperation, see jvmtiTagMap.cpp.
1237         //
1238         // That operation walks the reachable objects on its own, storing the marking
1239         // wavefront in the object marks. When it is done, it calls the CollectedHeap
1240         // to iterate over all objects to clean up the mess. When it reaches here,
1241         // the Shenandoah fwdptr resolution code encounters the marked objects with
1242         // NULL forwardee. Trying to act on that would crash the VM. Or fail the
1243         // asserts, should we go for resolve_forwarded_pointer(obj).
1244         //
1245         // Therefore, we have to dodge it by doing the raw access to forwardee, and
1246         // assuming the object had no forwardee, if that thing is NULL.
1247       } else {
1248         obj = fwd;
1249       }
1250       assert(oopDesc::is_oop(obj), "must be a valid oop");
1251       if (!_bitmap->is_marked((HeapWord*) obj)) {
1252         _bitmap->mark((HeapWord*) obj);
1253         _oop_stack->push(obj);
1254       }
1255     }
1256   }
1257 public:
1258   ObjectIterateScanRootClosure(MarkBitMap* bitmap, Stack<oop,mtGC>* oop_stack) :
1259     _bitmap(bitmap), _oop_stack(oop_stack) {}
1260   void do_oop(oop* p)       { do_oop_work(p); }
1261   void do_oop(narrowOop* p) { do_oop_work(p); }
1262 };
1263 
1264 /*
1265  * This is public API, used in preparation of object_iterate().
1266  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1267  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1268  * control, we call SH::make_tlabs_parsable().
1269  */
1270 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1271   // No-op.
1272 }
1273 
1274 /*
1275  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1276  *
1277  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1278  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1279  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1280  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1281  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1282  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1283  * wiped the bitmap in preparation for next marking).
1284  *
1285  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1286  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1287  * is allowed to report dead objects, but is not required to do so.
1288  */
1289 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1290   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1291   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1292     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1293     return;
1294   }
1295 
1296   // Reset bitmap
1297   _aux_bit_map.clear();
1298 
1299   Stack<oop,mtGC> oop_stack;
1300 
1301   // First, we process GC roots according to current GC cycle. This populates the work stack with initial objects.
1302   ShenandoahHeapIterationRootScanner rp;
1303   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1304 
1305   // If we are unloading classes right now, we should not touch weak roots,
1306   // on the off-chance we would evacuate them and make them live accidentally.
1307   // In other cases, we have to scan all roots.
1308   if (is_evacuation_in_progress() && unload_classes()) {
1309     rp.strong_roots_do(&oops);
1310   } else {
1311     rp.roots_do(&oops);
1312   }
1313 
1314   // Work through the oop stack to traverse heap.
1315   while (! oop_stack.is_empty()) {
1316     oop obj = oop_stack.pop();
1317     assert(oopDesc::is_oop(obj), "must be a valid oop");
1318     cl->do_object(obj);
1319     obj->oop_iterate(&oops);
1320   }
1321 
1322   assert(oop_stack.is_empty(), "should be empty");
1323 
1324   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1325     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1326   }
1327 }
1328 
1329 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1330   for (size_t i = 0; i < num_regions(); i++) {
1331     ShenandoahHeapRegion* current = get_region(i);
1332     blk->heap_region_do(current);
1333   }
1334 }
1335 
1336 class ShenandoahParallelHeapRegionTask : public AbstractGangTask {
1337 private:
1338   ShenandoahHeap* const _heap;
1339   ShenandoahHeapRegionClosure* const _blk;
1340 
1341   DEFINE_PAD_MINUS_SIZE(0, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile size_t));
1342   volatile size_t _index;
1343   DEFINE_PAD_MINUS_SIZE(1, DEFAULT_CACHE_LINE_SIZE, 0);
1344 
1345 public:
1346   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1347           AbstractGangTask("Parallel Region Task"),
1348           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1349 
1350   void work(uint worker_id) {
1351     size_t stride = ShenandoahParallelRegionStride;
1352 
1353     size_t max = _heap->num_regions();
1354     while (_index < max) {
1355       size_t cur = Atomic::add(&_index, stride) - stride;
1356       size_t start = cur;
1357       size_t end = MIN2(cur + stride, max);
1358       if (start >= max) break;
1359 
1360       for (size_t i = cur; i < end; i++) {
1361         ShenandoahHeapRegion* current = _heap->get_region(i);
1362         _blk->heap_region_do(current);
1363       }
1364     }
1365   }
1366 };
1367 
1368 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1369   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1370   if (num_regions() > ShenandoahParallelRegionStride) {
1371     ShenandoahParallelHeapRegionTask task(blk);
1372     workers()->run_task(&task);
1373   } else {
1374     heap_region_iterate(blk);
1375   }
1376 }
1377 
1378 class ShenandoahClearLivenessClosure : public ShenandoahHeapRegionClosure {
1379 private:
1380   ShenandoahMarkingContext* const _ctx;
1381 public:
1382   ShenandoahClearLivenessClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1383 
1384   void heap_region_do(ShenandoahHeapRegion* r) {
1385     if (r->is_active()) {
1386       r->clear_live_data();
1387       _ctx->capture_top_at_mark_start(r);
1388     } else {
1389       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number());
1390       assert(_ctx->top_at_mark_start(r) == r->top(),
1391              "Region " SIZE_FORMAT " should already have correct TAMS", r->region_number());
1392     }
1393   }
1394 
1395   bool is_thread_safe() { return true; }
1396 };
1397 
1398 void ShenandoahHeap::op_init_mark() {
1399   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1400   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
1401 
1402   assert(marking_context()->is_bitmap_clear(), "need clear marking bitmap");
1403   assert(!marking_context()->is_complete(), "should not be complete");
1404 
1405   if (ShenandoahVerify) {
1406     verifier()->verify_before_concmark();
1407   }
1408 
1409   if (VerifyBeforeGC) {
1410     Universe::verify();
1411   }
1412 
1413   set_concurrent_mark_in_progress(true);
1414   // We need to reset all TLABs because we'd lose marks on all objects allocated in them.
1415   {
1416     ShenandoahGCPhase phase(ShenandoahPhaseTimings::make_parsable);
1417     make_parsable(true);
1418   }
1419 
1420   {
1421     ShenandoahGCPhase phase(ShenandoahPhaseTimings::clear_liveness);
1422     ShenandoahClearLivenessClosure clc;
1423     parallel_heap_region_iterate(&clc);
1424   }
1425 
1426   // Make above changes visible to worker threads
1427   OrderAccess::fence();
1428 
1429   concurrent_mark()->mark_roots(ShenandoahPhaseTimings::scan_roots);
1430 
1431   if (UseTLAB) {
1432     ShenandoahGCPhase phase(ShenandoahPhaseTimings::resize_tlabs);
1433     resize_tlabs();
1434   }
1435 
1436   if (ShenandoahPacing) {
1437     pacer()->setup_for_mark();
1438   }
1439 }
1440 
1441 void ShenandoahHeap::op_mark() {
1442   concurrent_mark()->mark_from_roots();
1443 }
1444 
1445 class ShenandoahCompleteLivenessClosure : public ShenandoahHeapRegionClosure {
1446 private:
1447   ShenandoahMarkingContext* const _ctx;
1448 public:
1449   ShenandoahCompleteLivenessClosure() : _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
1450 
1451   void heap_region_do(ShenandoahHeapRegion* r) {
1452     if (r->is_active()) {
1453       HeapWord *tams = _ctx->top_at_mark_start(r);
1454       HeapWord *top = r->top();
1455       if (top > tams) {
1456         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1457       }
1458     } else {
1459       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number());
1460       assert(_ctx->top_at_mark_start(r) == r->top(),
1461              "Region " SIZE_FORMAT " should have correct TAMS", r->region_number());
1462     }
1463   }
1464 
1465   bool is_thread_safe() { return true; }
1466 };
1467 
1468 void ShenandoahHeap::op_final_mark() {
1469   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1470 
1471   // It is critical that we
1472   // evacuate roots right after finishing marking, so that we don't
1473   // get unmarked objects in the roots.
1474 
1475   if (!cancelled_gc()) {
1476     concurrent_mark()->finish_mark_from_roots(/* full_gc = */ false);
1477 
1478     // Marking is completed, deactivate SATB barrier
1479     set_concurrent_mark_in_progress(false);
1480     mark_complete_marking_context();
1481 
1482     parallel_cleaning(false /* full gc*/);
1483 
1484     if (has_forwarded_objects()) {
1485       // Degen may be caused by failed evacuation of roots
1486       if (is_degenerated_gc_in_progress()) {
1487         concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots);
1488       } else {
1489         concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::update_roots);
1490       }
1491       set_has_forwarded_objects(false);
1492    }
1493 
1494     if (ShenandoahVerify) {
1495       verifier()->verify_roots_no_forwarded();
1496     }
1497     // All allocations past TAMS are implicitly live, adjust the region data.
1498     // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1499     {
1500       ShenandoahGCPhase phase(ShenandoahPhaseTimings::complete_liveness);
1501       ShenandoahCompleteLivenessClosure cl;
1502       parallel_heap_region_iterate(&cl);
1503     }
1504 
1505     // Force the threads to reacquire their TLABs outside the collection set.
1506     {
1507       ShenandoahGCPhase phase(ShenandoahPhaseTimings::retire_tlabs);
1508       make_parsable(true);
1509     }
1510 
1511     // We are about to select the collection set, make sure it knows about
1512     // current pinning status. Also, this allows trashing more regions that
1513     // now have their pinning status dropped.
1514     {
1515       ShenandoahGCPhase phase(ShenandoahPhaseTimings::sync_pinned);
1516       sync_pinned_region_status();
1517     }
1518 
1519     // Trash the collection set left over from previous cycle, if any.
1520     {
1521       ShenandoahGCPhase phase(ShenandoahPhaseTimings::trash_cset);
1522       trash_cset_regions();
1523     }
1524 
1525     {
1526       ShenandoahGCPhase phase(ShenandoahPhaseTimings::prepare_evac);
1527 
1528       ShenandoahHeapLocker locker(lock());
1529       _collection_set->clear();
1530       _free_set->clear();
1531 
1532       heuristics()->choose_collection_set(_collection_set);
1533 
1534       _free_set->rebuild();
1535     }
1536 
1537     // If collection set has candidates, start evacuation.
1538     // Otherwise, bypass the rest of the cycle.
1539     if (!collection_set()->is_empty()) {
1540       ShenandoahGCPhase init_evac(ShenandoahPhaseTimings::init_evac);
1541 
1542       if (ShenandoahVerify) {
1543         verifier()->verify_before_evacuation();
1544       }
1545 
1546       set_evacuation_in_progress(true);
1547       // From here on, we need to update references.
1548       set_has_forwarded_objects(true);
1549 
1550       if (!is_degenerated_gc_in_progress()) {
1551         evacuate_and_update_roots();
1552       }
1553 
1554       if (ShenandoahPacing) {
1555         pacer()->setup_for_evac();
1556       }
1557 
1558       if (ShenandoahVerify) {
1559         if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) {
1560           ShenandoahRootVerifier::RootTypes types = ShenandoahRootVerifier::combine(ShenandoahRootVerifier::JNIHandleRoots, ShenandoahRootVerifier::WeakRoots);
1561           types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::CLDGRoots);
1562           verifier()->verify_roots_no_forwarded_except(types);
1563         } else {
1564           verifier()->verify_roots_no_forwarded();
1565         }
1566         verifier()->verify_during_evacuation();
1567       }
1568     } else {
1569       if (ShenandoahVerify) {
1570         verifier()->verify_after_concmark();
1571       }
1572 
1573       if (VerifyAfterGC) {
1574         Universe::verify();
1575       }
1576     }
1577 
1578   } else {
1579     // If this cycle was updating references, we need to keep the has_forwarded_objects
1580     // flag on, for subsequent phases to deal with it.
1581     concurrent_mark()->cancel();
1582     set_concurrent_mark_in_progress(false);
1583 
1584     if (process_references()) {
1585       // Abandon reference processing right away: pre-cleaning must have failed.
1586       ReferenceProcessor *rp = ref_processor();
1587       rp->disable_discovery();
1588       rp->abandon_partial_discovery();
1589       rp->verify_no_references_recorded();
1590     }
1591   }
1592 }
1593 
1594 void ShenandoahHeap::op_final_evac() {
1595   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1596 
1597   set_evacuation_in_progress(false);
1598 
1599   {
1600     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_retire_gclabs);
1601     retire_and_reset_gclabs();
1602   }
1603 
1604   if (ShenandoahVerify) {
1605     verifier()->verify_after_evacuation();
1606   }
1607 
1608   if (VerifyAfterGC) {
1609     Universe::verify();
1610   }
1611 }
1612 
1613 void ShenandoahHeap::op_conc_evac() {
1614   ShenandoahEvacuationTask task(this, _collection_set, true);
1615   workers()->run_task(&task);
1616 }
1617 
1618 void ShenandoahHeap::op_stw_evac() {
1619   ShenandoahEvacuationTask task(this, _collection_set, false);
1620   workers()->run_task(&task);
1621 }
1622 
1623 void ShenandoahHeap::op_updaterefs() {
1624   update_heap_references(true);
1625 }
1626 
1627 void ShenandoahHeap::op_cleanup() {
1628   free_set()->recycle_trash();
1629 }
1630 
1631 class ShenandoahConcurrentRootsEvacUpdateTask : public AbstractGangTask {
1632 private:
1633   ShenandoahVMRoots<true /*concurrent*/>        _vm_roots;
1634   ShenandoahWeakRoots<true /*concurrent*/>      _weak_roots;
1635   ShenandoahClassLoaderDataRoots<true /*concurrent*/, false /*single threaded*/> _cld_roots;
1636 
1637 public:
1638   ShenandoahConcurrentRootsEvacUpdateTask() :
1639     AbstractGangTask("Shenandoah Evacuate/Update Concurrent Roots Task") {
1640   }
1641 
1642   void work(uint worker_id) {
1643     ShenandoahEvacOOMScope oom;
1644     {
1645       // jni_roots and weak_roots are OopStorage backed roots, concurrent iteration
1646       // may race against OopStorage::release() calls.
1647       ShenandoahEvacUpdateOopStorageRootsClosure cl;
1648       _vm_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl);
1649       _weak_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl);
1650     }
1651 
1652     {
1653       ShenandoahEvacuateUpdateRootsClosure cl;
1654       CLDToOopClosure clds(&cl, ClassLoaderData::_claim_strong);
1655       _cld_roots.cld_do(&clds);
1656     }
1657   }
1658 };
1659 
1660 void ShenandoahHeap::op_roots() {
1661   if (is_evacuation_in_progress() &&
1662       ShenandoahConcurrentRoots::should_do_concurrent_roots()) {
1663     ShenandoahConcurrentRootsEvacUpdateTask task;
1664     workers()->run_task(&task);
1665   }
1666 }
1667 
1668 void ShenandoahHeap::op_reset() {
1669   reset_mark_bitmap();
1670 }
1671 
1672 void ShenandoahHeap::op_preclean() {
1673   concurrent_mark()->preclean_weak_refs();
1674 }
1675 
1676 void ShenandoahHeap::op_init_traversal() {
1677   traversal_gc()->init_traversal_collection();
1678 }
1679 
1680 void ShenandoahHeap::op_traversal() {
1681   traversal_gc()->concurrent_traversal_collection();
1682 }
1683 
1684 void ShenandoahHeap::op_final_traversal() {
1685   traversal_gc()->final_traversal_collection();
1686 }
1687 
1688 void ShenandoahHeap::op_full(GCCause::Cause cause) {
1689   ShenandoahMetricsSnapshot metrics;
1690   metrics.snap_before();
1691 
1692   full_gc()->do_it(cause);
1693   if (UseTLAB) {
1694     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_resize_tlabs);
1695     resize_all_tlabs();
1696   }
1697 
1698   metrics.snap_after();
1699 
1700   if (metrics.is_good_progress()) {
1701     _progress_last_gc.set();
1702   } else {
1703     // Nothing to do. Tell the allocation path that we have failed to make
1704     // progress, and it can finally fail.
1705     _progress_last_gc.unset();
1706   }
1707 }
1708 
1709 void ShenandoahHeap::op_degenerated(ShenandoahDegenPoint point) {
1710   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
1711   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
1712   // some phase, we have to upgrade the Degenerate GC to Full GC.
1713 
1714   clear_cancelled_gc();
1715 
1716   ShenandoahMetricsSnapshot metrics;
1717   metrics.snap_before();
1718 
1719   switch (point) {
1720     case _degenerated_traversal:
1721       {
1722         // Drop the collection set. Note: this leaves some already forwarded objects
1723         // behind, which may be problematic, see comments for ShenandoahEvacAssist
1724         // workarounds in ShenandoahTraversalHeuristics.
1725 
1726         ShenandoahHeapLocker locker(lock());
1727         collection_set()->clear_current_index();
1728         for (size_t i = 0; i < collection_set()->count(); i++) {
1729           ShenandoahHeapRegion* r = collection_set()->next();
1730           r->make_regular_bypass();
1731         }
1732         collection_set()->clear();
1733       }
1734       op_final_traversal();
1735       op_cleanup();
1736       return;
1737 
1738     // The cases below form the Duff's-like device: it describes the actual GC cycle,
1739     // but enters it at different points, depending on which concurrent phase had
1740     // degenerated.
1741 
1742     case _degenerated_outside_cycle:
1743       // We have degenerated from outside the cycle, which means something is bad with
1744       // the heap, most probably heavy humongous fragmentation, or we are very low on free
1745       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
1746       // we can do the most aggressive degen cycle, which includes processing references and
1747       // class unloading, unless those features are explicitly disabled.
1748       //
1749       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
1750       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
1751       set_process_references(heuristics()->can_process_references());
1752       set_unload_classes(heuristics()->can_unload_classes());
1753 
1754       if (is_traversal_mode()) {
1755         // Not possible to degenerate from here, upgrade to Full GC right away.
1756         cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1757         op_degenerated_fail();
1758         return;
1759       }
1760 
1761       op_reset();
1762 
1763       op_init_mark();
1764       if (cancelled_gc()) {
1765         op_degenerated_fail();
1766         return;
1767       }
1768 
1769     case _degenerated_mark:
1770       op_final_mark();
1771       if (cancelled_gc()) {
1772         op_degenerated_fail();
1773         return;
1774       }
1775 
1776       op_cleanup();
1777 
1778     case _degenerated_evac:
1779       // If heuristics thinks we should do the cycle, this flag would be set,
1780       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
1781       if (is_evacuation_in_progress()) {
1782 
1783         // Degeneration under oom-evac protocol might have left some objects in
1784         // collection set un-evacuated. Restart evacuation from the beginning to
1785         // capture all objects. For all the objects that are already evacuated,
1786         // it would be a simple check, which is supposed to be fast. This is also
1787         // safe to do even without degeneration, as CSet iterator is at beginning
1788         // in preparation for evacuation anyway.
1789         //
1790         // Before doing that, we need to make sure we never had any cset-pinned
1791         // regions. This may happen if allocation failure happened when evacuating
1792         // the about-to-be-pinned object, oom-evac protocol left the object in
1793         // the collection set, and then the pin reached the cset region. If we continue
1794         // the cycle here, we would trash the cset and alive objects in it. To avoid
1795         // it, we fail degeneration right away and slide into Full GC to recover.
1796 
1797         {
1798           sync_pinned_region_status();
1799           collection_set()->clear_current_index();
1800 
1801           ShenandoahHeapRegion* r;
1802           while ((r = collection_set()->next()) != NULL) {
1803             if (r->is_pinned()) {
1804               cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1805               op_degenerated_fail();
1806               return;
1807             }
1808           }
1809 
1810           collection_set()->clear_current_index();
1811         }
1812 
1813         op_stw_evac();
1814         if (cancelled_gc()) {
1815           op_degenerated_fail();
1816           return;
1817         }
1818       }
1819 
1820       // If heuristics thinks we should do the cycle, this flag would be set,
1821       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
1822       if (has_forwarded_objects()) {
1823         op_init_updaterefs();
1824         if (cancelled_gc()) {
1825           op_degenerated_fail();
1826           return;
1827         }
1828       }
1829 
1830     case _degenerated_updaterefs:
1831       if (has_forwarded_objects()) {
1832         op_final_updaterefs();
1833         if (cancelled_gc()) {
1834           op_degenerated_fail();
1835           return;
1836         }
1837       }
1838 
1839       op_cleanup();
1840       break;
1841 
1842     default:
1843       ShouldNotReachHere();
1844   }
1845 
1846   if (ShenandoahVerify) {
1847     verifier()->verify_after_degenerated();
1848   }
1849 
1850   if (VerifyAfterGC) {
1851     Universe::verify();
1852   }
1853 
1854   metrics.snap_after();
1855 
1856   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
1857   // because that probably means the heap is overloaded and/or fragmented.
1858   if (!metrics.is_good_progress()) {
1859     _progress_last_gc.unset();
1860     cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1861     op_degenerated_futile();
1862   } else {
1863     _progress_last_gc.set();
1864   }
1865 }
1866 
1867 void ShenandoahHeap::op_degenerated_fail() {
1868   log_info(gc)("Cannot finish degeneration, upgrading to Full GC");
1869   shenandoah_policy()->record_degenerated_upgrade_to_full();
1870   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1871 }
1872 
1873 void ShenandoahHeap::op_degenerated_futile() {
1874   shenandoah_policy()->record_degenerated_upgrade_to_full();
1875   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1876 }
1877 
1878 void ShenandoahHeap::force_satb_flush_all_threads() {
1879   if (!is_concurrent_mark_in_progress() && !is_concurrent_traversal_in_progress()) {
1880     // No need to flush SATBs
1881     return;
1882   }
1883 
1884   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1885     ShenandoahThreadLocalData::set_force_satb_flush(t, true);
1886   }
1887   // The threads are not "acquiring" their thread-local data, but it does not
1888   // hurt to "release" the updates here anyway.
1889   OrderAccess::fence();
1890 }
1891 
1892 void ShenandoahHeap::set_gc_state_all_threads(char state) {
1893   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1894     ShenandoahThreadLocalData::set_gc_state(t, state);
1895   }
1896 }
1897 
1898 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1899   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1900   _gc_state.set_cond(mask, value);
1901   set_gc_state_all_threads(_gc_state.raw_value());
1902 }
1903 
1904 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1905   if (has_forwarded_objects()) {
1906     set_gc_state_mask(MARKING | UPDATEREFS, in_progress);
1907   } else {
1908     set_gc_state_mask(MARKING, in_progress);
1909   }
1910   ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1911 }
1912 
1913 void ShenandoahHeap::set_concurrent_traversal_in_progress(bool in_progress) {
1914    set_gc_state_mask(TRAVERSAL, in_progress);
1915    ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1916 }
1917 
1918 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1919   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1920   set_gc_state_mask(EVACUATION, in_progress);
1921 }
1922 
1923 void ShenandoahHeap::ref_processing_init() {
1924   assert(_max_workers > 0, "Sanity");
1925 
1926   _ref_processor =
1927     new ReferenceProcessor(&_subject_to_discovery,  // is_subject_to_discovery
1928                            ParallelRefProcEnabled,  // MT processing
1929                            _max_workers,            // Degree of MT processing
1930                            true,                    // MT discovery
1931                            _max_workers,            // Degree of MT discovery
1932                            false,                   // Reference discovery is not atomic
1933                            NULL,                    // No closure, should be installed before use
1934                            true);                   // Scale worker threads
1935 
1936   shenandoah_assert_rp_isalive_not_installed();
1937 }
1938 
1939 GCTracer* ShenandoahHeap::tracer() {
1940   return shenandoah_policy()->tracer();
1941 }
1942 
1943 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1944   return _free_set->used();
1945 }
1946 
1947 bool ShenandoahHeap::try_cancel_gc() {
1948   while (true) {
1949     jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
1950     if (prev == CANCELLABLE) return true;
1951     else if (prev == CANCELLED) return false;
1952     assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers");
1953     assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED");
1954     if (Thread::current()->is_Java_thread()) {
1955       // We need to provide a safepoint here, otherwise we might
1956       // spin forever if a SP is pending.
1957       ThreadBlockInVM sp(JavaThread::current());
1958       SpinPause();
1959     }
1960   }
1961 }
1962 
1963 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1964   if (try_cancel_gc()) {
1965     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1966     log_info(gc)("%s", msg.buffer());
1967     Events::log(Thread::current(), "%s", msg.buffer());
1968   }
1969 }
1970 
1971 uint ShenandoahHeap::max_workers() {
1972   return _max_workers;
1973 }
1974 
1975 void ShenandoahHeap::stop() {
1976   // The shutdown sequence should be able to terminate when GC is running.
1977 
1978   // Step 0. Notify policy to disable event recording.
1979   _shenandoah_policy->record_shutdown();
1980 
1981   // Step 1. Notify control thread that we are in shutdown.
1982   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1983   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1984   control_thread()->prepare_for_graceful_shutdown();
1985 
1986   // Step 2. Notify GC workers that we are cancelling GC.
1987   cancel_gc(GCCause::_shenandoah_stop_vm);
1988 
1989   // Step 3. Wait until GC worker exits normally.
1990   control_thread()->stop();
1991 
1992   // Step 4. Stop String Dedup thread if it is active
1993   if (ShenandoahStringDedup::is_enabled()) {
1994     ShenandoahStringDedup::stop();
1995   }
1996 }
1997 
1998 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
1999   if (!unload_classes()) return;
2000   bool purged_class;
2001 
2002   // Unload classes and purge SystemDictionary.
2003   {
2004     ShenandoahGCPhase phase(full_gc ?
2005                             ShenandoahPhaseTimings::full_gc_purge_class_unload :
2006                             ShenandoahPhaseTimings::purge_class_unload);
2007     purged_class = SystemDictionary::do_unloading(gc_timer());
2008   }
2009 
2010   {
2011     ShenandoahGCPhase phase(full_gc ?
2012                             ShenandoahPhaseTimings::full_gc_purge_par :
2013                             ShenandoahPhaseTimings::purge_par);
2014     ShenandoahIsAliveSelector is_alive;
2015     uint num_workers = _workers->active_workers();
2016     ShenandoahClassUnloadingTask unlink_task(is_alive.is_alive_closure(), num_workers, purged_class);
2017     _workers->run_task(&unlink_task);
2018   }
2019 
2020   {
2021     ShenandoahGCPhase phase(full_gc ?
2022                             ShenandoahPhaseTimings::full_gc_purge_cldg :
2023                             ShenandoahPhaseTimings::purge_cldg);
2024     ClassLoaderDataGraph::purge();
2025   }
2026   // Resize and verify metaspace
2027   MetaspaceGC::compute_new_size();
2028   MetaspaceUtils::verify_metrics();
2029 }
2030 
2031 // Process leftover weak oops: update them, if needed or assert they do not
2032 // need updating otherwise.
2033 // Weak processor API requires us to visit the oops, even if we are not doing
2034 // anything to them.
2035 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
2036   ShenandoahGCPhase root_phase(full_gc ?
2037                                ShenandoahPhaseTimings::full_gc_purge :
2038                                ShenandoahPhaseTimings::purge);
2039   uint num_workers = _workers->active_workers();
2040   ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
2041                                                ShenandoahPhaseTimings::full_gc_purge_par :
2042                                                ShenandoahPhaseTimings::purge_par;
2043   // Cleanup weak roots
2044   ShenandoahGCPhase phase(timing_phase);
2045   if (has_forwarded_objects()) {
2046     if (is_traversal_mode()) {
2047       ShenandoahForwardedIsAliveClosure is_alive;
2048       ShenandoahTraversalUpdateRefsClosure keep_alive;
2049       ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahTraversalUpdateRefsClosure>
2050         cleaning_task(&is_alive, &keep_alive, num_workers);
2051       _workers->run_task(&cleaning_task);
2052     } else {
2053       ShenandoahForwardedIsAliveClosure is_alive;
2054       ShenandoahUpdateRefsClosure keep_alive;
2055       ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure>
2056         cleaning_task(&is_alive, &keep_alive, num_workers);
2057       _workers->run_task(&cleaning_task);
2058     }
2059   } else {
2060     ShenandoahIsAliveClosure is_alive;
2061 #ifdef ASSERT
2062   ShenandoahAssertNotForwardedClosure verify_cl;
2063   ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
2064     cleaning_task(&is_alive, &verify_cl, num_workers);
2065 #else
2066   ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
2067     cleaning_task(&is_alive, &do_nothing_cl, num_workers);
2068 #endif
2069     _workers->run_task(&cleaning_task);
2070   }
2071 }
2072 
2073 void ShenandoahHeap::parallel_cleaning(bool full_gc) {
2074   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2075   stw_process_weak_roots(full_gc);
2076   stw_unload_classes(full_gc);
2077 }
2078 
2079 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
2080   if (is_traversal_mode()) {
2081     set_gc_state_mask(HAS_FORWARDED | UPDATEREFS, cond);
2082   } else {
2083     set_gc_state_mask(HAS_FORWARDED, cond);
2084   }
2085 
2086 }
2087 
2088 void ShenandoahHeap::set_process_references(bool pr) {
2089   _process_references.set_cond(pr);
2090 }
2091 
2092 void ShenandoahHeap::set_unload_classes(bool uc) {
2093   _unload_classes.set_cond(uc);
2094 }
2095 
2096 bool ShenandoahHeap::process_references() const {
2097   return _process_references.is_set();
2098 }
2099 
2100 bool ShenandoahHeap::unload_classes() const {
2101   return _unload_classes.is_set();
2102 }
2103 
2104 address ShenandoahHeap::in_cset_fast_test_addr() {
2105   ShenandoahHeap* heap = ShenandoahHeap::heap();
2106   assert(heap->collection_set() != NULL, "Sanity");
2107   return (address) heap->collection_set()->biased_map_address();
2108 }
2109 
2110 address ShenandoahHeap::cancelled_gc_addr() {
2111   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
2112 }
2113 
2114 address ShenandoahHeap::gc_state_addr() {
2115   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
2116 }
2117 
2118 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
2119   return Atomic::load_acquire(&_bytes_allocated_since_gc_start);
2120 }
2121 
2122 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
2123   Atomic::release_store_fence(&_bytes_allocated_since_gc_start, (size_t)0);
2124 }
2125 
2126 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2127   _degenerated_gc_in_progress.set_cond(in_progress);
2128 }
2129 
2130 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2131   _full_gc_in_progress.set_cond(in_progress);
2132 }
2133 
2134 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2135   assert (is_full_gc_in_progress(), "should be");
2136   _full_gc_move_in_progress.set_cond(in_progress);
2137 }
2138 
2139 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2140   set_gc_state_mask(UPDATEREFS, in_progress);
2141 }
2142 
2143 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2144   ShenandoahCodeRoots::add_nmethod(nm);
2145 }
2146 
2147 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2148   ShenandoahCodeRoots::remove_nmethod(nm);
2149 }
2150 
2151 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2152   heap_region_containing(o)->record_pin();
2153   return o;
2154 }
2155 
2156 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2157   heap_region_containing(o)->record_unpin();
2158 }
2159 
2160 void ShenandoahHeap::sync_pinned_region_status() {
2161   ShenandoahHeapLocker locker(lock());
2162 
2163   for (size_t i = 0; i < num_regions(); i++) {
2164     ShenandoahHeapRegion *r = get_region(i);
2165     if (r->is_active()) {
2166       if (r->is_pinned()) {
2167         if (r->pin_count() == 0) {
2168           r->make_unpinned();
2169         }
2170       } else {
2171         if (r->pin_count() > 0) {
2172           r->make_pinned();
2173         }
2174       }
2175     }
2176   }
2177 
2178   assert_pinned_region_status();
2179 }
2180 
2181 #ifdef ASSERT
2182 void ShenandoahHeap::assert_pinned_region_status() {
2183   for (size_t i = 0; i < num_regions(); i++) {
2184     ShenandoahHeapRegion* r = get_region(i);
2185     assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
2186            "Region " SIZE_FORMAT " pinning status is inconsistent", i);
2187   }
2188 }
2189 #endif
2190 
2191 GCTimer* ShenandoahHeap::gc_timer() const {
2192   return _gc_timer;
2193 }
2194 
2195 #ifdef ASSERT
2196 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2197   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2198 
2199   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2200     if (UseDynamicNumberOfGCThreads ||
2201         (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) {
2202       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
2203     } else {
2204       // Use ParallelGCThreads inside safepoints
2205       assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints");
2206     }
2207   } else {
2208     if (UseDynamicNumberOfGCThreads ||
2209         (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) {
2210       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
2211     } else {
2212       // Use ConcGCThreads outside safepoints
2213       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2214     }
2215   }
2216 }
2217 #endif
2218 
2219 ShenandoahVerifier* ShenandoahHeap::verifier() {
2220   guarantee(ShenandoahVerify, "Should be enabled");
2221   assert (_verifier != NULL, "sanity");
2222   return _verifier;
2223 }
2224 
2225 template<class T>
2226 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
2227 private:
2228   T cl;
2229   ShenandoahHeap* _heap;
2230   ShenandoahRegionIterator* _regions;
2231   bool _concurrent;
2232 public:
2233   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions, bool concurrent) :
2234     AbstractGangTask("Concurrent Update References Task"),
2235     cl(T()),
2236     _heap(ShenandoahHeap::heap()),
2237     _regions(regions),
2238     _concurrent(concurrent) {
2239   }
2240 
2241   void work(uint worker_id) {
2242     if (_concurrent) {
2243       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2244       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2245       do_work();
2246     } else {
2247       ShenandoahParallelWorkerSession worker_session(worker_id);
2248       do_work();
2249     }
2250   }
2251 
2252 private:
2253   void do_work() {
2254     ShenandoahHeapRegion* r = _regions->next();
2255     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2256     while (r != NULL) {
2257       HeapWord* top_at_start_ur = r->concurrent_iteration_safe_limit();
2258       assert (top_at_start_ur >= r->bottom(), "sanity");
2259       if (r->is_active() && !r->is_cset()) {
2260         _heap->marked_object_oop_iterate(r, &cl, top_at_start_ur);
2261       }
2262       if (ShenandoahPacing) {
2263         _heap->pacer()->report_updaterefs(pointer_delta(top_at_start_ur, r->bottom()));
2264       }
2265       if (_heap->check_cancelled_gc_and_yield(_concurrent)) {
2266         return;
2267       }
2268       r = _regions->next();
2269     }
2270   }
2271 };
2272 
2273 void ShenandoahHeap::update_heap_references(bool concurrent) {
2274   ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsClosure> task(&_update_refs_iterator, concurrent);
2275   workers()->run_task(&task);
2276 }
2277 
2278 void ShenandoahHeap::op_init_updaterefs() {
2279   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2280 
2281   set_evacuation_in_progress(false);
2282 
2283   {
2284     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_retire_gclabs);
2285     retire_and_reset_gclabs();
2286   }
2287 
2288   if (ShenandoahVerify) {
2289     if (!is_degenerated_gc_in_progress()) {
2290       verifier()->verify_roots_no_forwarded_except(ShenandoahRootVerifier::ThreadRoots);
2291     }
2292     verifier()->verify_before_updaterefs();
2293   }
2294 
2295   set_update_refs_in_progress(true);
2296 
2297   {
2298     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_prepare);
2299 
2300     make_parsable(true);
2301     for (uint i = 0; i < num_regions(); i++) {
2302       ShenandoahHeapRegion* r = get_region(i);
2303       r->set_concurrent_iteration_safe_limit(r->top());
2304     }
2305 
2306     // Reset iterator.
2307     _update_refs_iterator.reset();
2308   }
2309 
2310   if (ShenandoahPacing) {
2311     pacer()->setup_for_updaterefs();
2312   }
2313 }
2314 
2315 void ShenandoahHeap::op_final_updaterefs() {
2316   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2317 
2318   // Check if there is left-over work, and finish it
2319   if (_update_refs_iterator.has_next()) {
2320     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_finish_work);
2321 
2322     // Finish updating references where we left off.
2323     clear_cancelled_gc();
2324     update_heap_references(false);
2325   }
2326 
2327   // Clear cancelled GC, if set. On cancellation path, the block before would handle
2328   // everything. On degenerated paths, cancelled gc would not be set anyway.
2329   if (cancelled_gc()) {
2330     clear_cancelled_gc();
2331   }
2332   assert(!cancelled_gc(), "Should have been done right before");
2333 
2334   if (ShenandoahVerify && !is_degenerated_gc_in_progress()) {
2335     verifier()->verify_roots_no_forwarded_except(ShenandoahRootVerifier::ThreadRoots);
2336   }
2337 
2338   if (is_degenerated_gc_in_progress()) {
2339     concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots);
2340   } else {
2341     concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::final_update_refs_roots);
2342   }
2343 
2344   // Has to be done before cset is clear
2345   if (ShenandoahVerify) {
2346     verifier()->verify_roots_in_to_space();
2347   }
2348 
2349   // Drop unnecessary "pinned" state from regions that does not have CP marks
2350   // anymore, as this would allow trashing them below.
2351   {
2352     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_sync_pinned);
2353     sync_pinned_region_status();
2354   }
2355 
2356   {
2357     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_trash_cset);
2358     trash_cset_regions();
2359   }
2360 
2361   set_has_forwarded_objects(false);
2362   set_update_refs_in_progress(false);
2363 
2364   if (ShenandoahVerify) {
2365     verifier()->verify_after_updaterefs();
2366   }
2367 
2368   if (VerifyAfterGC) {
2369     Universe::verify();
2370   }
2371 
2372   {
2373     ShenandoahHeapLocker locker(lock());
2374     _free_set->rebuild();
2375   }
2376 }
2377 
2378 #ifdef ASSERT
2379 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() {
2380   _lock.assert_owned_by_current_thread();
2381 }
2382 
2383 void ShenandoahHeap::assert_heaplock_not_owned_by_current_thread() {
2384   _lock.assert_not_owned_by_current_thread();
2385 }
2386 
2387 void ShenandoahHeap::assert_heaplock_or_safepoint() {
2388   _lock.assert_owned_by_current_thread_or_safepoint();
2389 }
2390 #endif
2391 
2392 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2393   print_on(st);
2394   print_heap_regions_on(st);
2395 }
2396 
2397 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2398   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2399 
2400   size_t regions_from = _bitmap_regions_per_slice * slice;
2401   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2402   for (size_t g = regions_from; g < regions_to; g++) {
2403     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2404     if (skip_self && g == r->region_number()) continue;
2405     if (get_region(g)->is_committed()) {
2406       return true;
2407     }
2408   }
2409   return false;
2410 }
2411 
2412 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2413   assert_heaplock_owned_by_current_thread();
2414 
2415   // Bitmaps in special regions do not need commits
2416   if (_bitmap_region_special) {
2417     return true;
2418   }
2419 
2420   if (is_bitmap_slice_committed(r, true)) {
2421     // Some other region from the group is already committed, meaning the bitmap
2422     // slice is already committed, we exit right away.
2423     return true;
2424   }
2425 
2426   // Commit the bitmap slice:
2427   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2428   size_t off = _bitmap_bytes_per_slice * slice;
2429   size_t len = _bitmap_bytes_per_slice;
2430   if (!os::commit_memory((char*)_bitmap_region.start() + off, len, false)) {
2431     return false;
2432   }
2433   return true;
2434 }
2435 
2436 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2437   assert_heaplock_owned_by_current_thread();
2438 
2439   // Bitmaps in special regions do not need uncommits
2440   if (_bitmap_region_special) {
2441     return true;
2442   }
2443 
2444   if (is_bitmap_slice_committed(r, true)) {
2445     // Some other region from the group is still committed, meaning the bitmap
2446     // slice is should stay committed, exit right away.
2447     return true;
2448   }
2449 
2450   // Uncommit the bitmap slice:
2451   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2452   size_t off = _bitmap_bytes_per_slice * slice;
2453   size_t len = _bitmap_bytes_per_slice;
2454   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2455     return false;
2456   }
2457   return true;
2458 }
2459 
2460 void ShenandoahHeap::safepoint_synchronize_begin() {
2461   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2462     SuspendibleThreadSet::synchronize();
2463   }
2464 }
2465 
2466 void ShenandoahHeap::safepoint_synchronize_end() {
2467   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2468     SuspendibleThreadSet::desynchronize();
2469   }
2470 }
2471 
2472 void ShenandoahHeap::vmop_entry_init_mark() {
2473   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2474   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2475   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark_gross);
2476 
2477   try_inject_alloc_failure();
2478   VM_ShenandoahInitMark op;
2479   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
2480 }
2481 
2482 void ShenandoahHeap::vmop_entry_final_mark() {
2483   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2484   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2485   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark_gross);
2486 
2487   try_inject_alloc_failure();
2488   VM_ShenandoahFinalMarkStartEvac op;
2489   VMThread::execute(&op); // jump to entry_final_mark under safepoint
2490 }
2491 
2492 void ShenandoahHeap::vmop_entry_final_evac() {
2493   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2494   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2495   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_gross);
2496 
2497   VM_ShenandoahFinalEvac op;
2498   VMThread::execute(&op); // jump to entry_final_evac under safepoint
2499 }
2500 
2501 void ShenandoahHeap::vmop_entry_init_updaterefs() {
2502   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2503   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2504   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_gross);
2505 
2506   try_inject_alloc_failure();
2507   VM_ShenandoahInitUpdateRefs op;
2508   VMThread::execute(&op);
2509 }
2510 
2511 void ShenandoahHeap::vmop_entry_final_updaterefs() {
2512   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2513   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2514   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_gross);
2515 
2516   try_inject_alloc_failure();
2517   VM_ShenandoahFinalUpdateRefs op;
2518   VMThread::execute(&op);
2519 }
2520 
2521 void ShenandoahHeap::vmop_entry_init_traversal() {
2522   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2523   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2524   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc_gross);
2525 
2526   try_inject_alloc_failure();
2527   VM_ShenandoahInitTraversalGC op;
2528   VMThread::execute(&op);
2529 }
2530 
2531 void ShenandoahHeap::vmop_entry_final_traversal() {
2532   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2533   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2534   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc_gross);
2535 
2536   try_inject_alloc_failure();
2537   VM_ShenandoahFinalTraversalGC op;
2538   VMThread::execute(&op);
2539 }
2540 
2541 void ShenandoahHeap::vmop_entry_full(GCCause::Cause cause) {
2542   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2543   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2544   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_gross);
2545 
2546   try_inject_alloc_failure();
2547   VM_ShenandoahFullGC op(cause);
2548   VMThread::execute(&op);
2549 }
2550 
2551 void ShenandoahHeap::vmop_degenerated(ShenandoahDegenPoint point) {
2552   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2553   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2554   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_gross);
2555 
2556   VM_ShenandoahDegeneratedGC degenerated_gc((int)point);
2557   VMThread::execute(&degenerated_gc);
2558 }
2559 
2560 void ShenandoahHeap::entry_init_mark() {
2561   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2562   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark);
2563   const char* msg = init_mark_event_message();
2564   GCTraceTime(Info, gc) time(msg, gc_timer());
2565   EventMark em("%s", msg);
2566 
2567   ShenandoahWorkerScope scope(workers(),
2568                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
2569                               "init marking");
2570 
2571   op_init_mark();
2572 }
2573 
2574 void ShenandoahHeap::entry_final_mark() {
2575   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2576   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark);
2577   const char* msg = final_mark_event_message();
2578   GCTraceTime(Info, gc) time(msg, gc_timer());
2579   EventMark em("%s", msg);
2580 
2581   ShenandoahWorkerScope scope(workers(),
2582                               ShenandoahWorkerPolicy::calc_workers_for_final_marking(),
2583                               "final marking");
2584 
2585   op_final_mark();
2586 }
2587 
2588 void ShenandoahHeap::entry_final_evac() {
2589   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2590   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac);
2591   static const char* msg = "Pause Final Evac";
2592   GCTraceTime(Info, gc) time(msg, gc_timer());
2593   EventMark em("%s", msg);
2594 
2595   op_final_evac();
2596 }
2597 
2598 void ShenandoahHeap::entry_init_updaterefs() {
2599   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2600   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs);
2601 
2602   static const char* msg = "Pause Init Update Refs";
2603   GCTraceTime(Info, gc) time(msg, gc_timer());
2604   EventMark em("%s", msg);
2605 
2606   // No workers used in this phase, no setup required
2607 
2608   op_init_updaterefs();
2609 }
2610 
2611 void ShenandoahHeap::entry_final_updaterefs() {
2612   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2613   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs);
2614 
2615   static const char* msg = "Pause Final Update Refs";
2616   GCTraceTime(Info, gc) time(msg, gc_timer());
2617   EventMark em("%s", msg);
2618 
2619   ShenandoahWorkerScope scope(workers(),
2620                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
2621                               "final reference update");
2622 
2623   op_final_updaterefs();
2624 }
2625 
2626 void ShenandoahHeap::entry_init_traversal() {
2627   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2628   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc);
2629 
2630   static const char* msg = "Pause Init Traversal";
2631   GCTraceTime(Info, gc) time(msg, gc_timer());
2632   EventMark em("%s", msg);
2633 
2634   ShenandoahWorkerScope scope(workers(),
2635                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2636                               "init traversal");
2637 
2638   op_init_traversal();
2639 }
2640 
2641 void ShenandoahHeap::entry_final_traversal() {
2642   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2643   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc);
2644 
2645   static const char* msg = "Pause Final Traversal";
2646   GCTraceTime(Info, gc) time(msg, gc_timer());
2647   EventMark em("%s", msg);
2648 
2649   ShenandoahWorkerScope scope(workers(),
2650                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2651                               "final traversal");
2652 
2653   op_final_traversal();
2654 }
2655 
2656 void ShenandoahHeap::entry_full(GCCause::Cause cause) {
2657   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2658   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc);
2659 
2660   static const char* msg = "Pause Full";
2661   GCTraceTime(Info, gc) time(msg, gc_timer(), cause, true);
2662   EventMark em("%s", msg);
2663 
2664   ShenandoahWorkerScope scope(workers(),
2665                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
2666                               "full gc");
2667 
2668   op_full(cause);
2669 }
2670 
2671 void ShenandoahHeap::entry_degenerated(int point) {
2672   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2673   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc);
2674 
2675   ShenandoahDegenPoint dpoint = (ShenandoahDegenPoint)point;
2676   const char* msg = degen_event_message(dpoint);
2677   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2678   EventMark em("%s", msg);
2679 
2680   ShenandoahWorkerScope scope(workers(),
2681                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
2682                               "stw degenerated gc");
2683 
2684   set_degenerated_gc_in_progress(true);
2685   op_degenerated(dpoint);
2686   set_degenerated_gc_in_progress(false);
2687 }
2688 
2689 void ShenandoahHeap::entry_mark() {
2690   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2691 
2692   const char* msg = conc_mark_event_message();
2693   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2694   EventMark em("%s", msg);
2695 
2696   ShenandoahWorkerScope scope(workers(),
2697                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
2698                               "concurrent marking");
2699 
2700   try_inject_alloc_failure();
2701   op_mark();
2702 }
2703 
2704 void ShenandoahHeap::entry_evac() {
2705   ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac);
2706   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2707 
2708   static const char* msg = "Concurrent evacuation";
2709   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2710   EventMark em("%s", msg);
2711 
2712   ShenandoahWorkerScope scope(workers(),
2713                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
2714                               "concurrent evacuation");
2715 
2716   try_inject_alloc_failure();
2717   op_conc_evac();
2718 }
2719 
2720 void ShenandoahHeap::entry_updaterefs() {
2721   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs);
2722 
2723   static const char* msg = "Concurrent update references";
2724   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2725   EventMark em("%s", msg);
2726 
2727   ShenandoahWorkerScope scope(workers(),
2728                               ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(),
2729                               "concurrent reference update");
2730 
2731   try_inject_alloc_failure();
2732   op_updaterefs();
2733 }
2734 
2735 void ShenandoahHeap::entry_roots() {
2736   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_roots);
2737 
2738   static const char* msg = "Concurrent roots processing";
2739   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2740   EventMark em("%s", msg);
2741 
2742   ShenandoahWorkerScope scope(workers(),
2743                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
2744                               "concurrent root processing");
2745 
2746   try_inject_alloc_failure();
2747   op_roots();
2748 }
2749 
2750 void ShenandoahHeap::entry_cleanup() {
2751   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup);
2752 
2753   static const char* msg = "Concurrent cleanup";
2754   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2755   EventMark em("%s", msg);
2756 
2757   // This phase does not use workers, no need for setup
2758 
2759   try_inject_alloc_failure();
2760   op_cleanup();
2761 }
2762 
2763 void ShenandoahHeap::entry_reset() {
2764   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_reset);
2765 
2766   static const char* msg = "Concurrent reset";
2767   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2768   EventMark em("%s", msg);
2769 
2770   ShenandoahWorkerScope scope(workers(),
2771                               ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
2772                               "concurrent reset");
2773 
2774   try_inject_alloc_failure();
2775   op_reset();
2776 }
2777 
2778 void ShenandoahHeap::entry_preclean() {
2779   if (ShenandoahPreclean && process_references()) {
2780     static const char* msg = "Concurrent precleaning";
2781     GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2782     EventMark em("%s", msg);
2783 
2784     ShenandoahGCPhase conc_preclean(ShenandoahPhaseTimings::conc_preclean);
2785 
2786     ShenandoahWorkerScope scope(workers(),
2787                                 ShenandoahWorkerPolicy::calc_workers_for_conc_preclean(),
2788                                 "concurrent preclean",
2789                                 /* check_workers = */ false);
2790 
2791     try_inject_alloc_failure();
2792     op_preclean();
2793   }
2794 }
2795 
2796 void ShenandoahHeap::entry_traversal() {
2797   static const char* msg = "Concurrent traversal";
2798   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2799   EventMark em("%s", msg);
2800 
2801   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2802 
2803   ShenandoahWorkerScope scope(workers(),
2804                               ShenandoahWorkerPolicy::calc_workers_for_conc_traversal(),
2805                               "concurrent traversal");
2806 
2807   try_inject_alloc_failure();
2808   op_traversal();
2809 }
2810 
2811 void ShenandoahHeap::entry_uncommit(double shrink_before) {
2812   static const char *msg = "Concurrent uncommit";
2813   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2814   EventMark em("%s", msg);
2815 
2816   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_uncommit);
2817 
2818   op_uncommit(shrink_before);
2819 }
2820 
2821 void ShenandoahHeap::try_inject_alloc_failure() {
2822   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2823     _inject_alloc_failure.set();
2824     os::naked_short_sleep(1);
2825     if (cancelled_gc()) {
2826       log_info(gc)("Allocation failure was successfully injected");
2827     }
2828   }
2829 }
2830 
2831 bool ShenandoahHeap::should_inject_alloc_failure() {
2832   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2833 }
2834 
2835 void ShenandoahHeap::initialize_serviceability() {
2836   _memory_pool = new ShenandoahMemoryPool(this);
2837   _cycle_memory_manager.add_pool(_memory_pool);
2838   _stw_memory_manager.add_pool(_memory_pool);
2839 }
2840 
2841 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2842   GrowableArray<GCMemoryManager*> memory_managers(2);
2843   memory_managers.append(&_cycle_memory_manager);
2844   memory_managers.append(&_stw_memory_manager);
2845   return memory_managers;
2846 }
2847 
2848 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2849   GrowableArray<MemoryPool*> memory_pools(1);
2850   memory_pools.append(_memory_pool);
2851   return memory_pools;
2852 }
2853 
2854 MemoryUsage ShenandoahHeap::memory_usage() {
2855   return _memory_pool->get_memory_usage();
2856 }
2857 
2858 void ShenandoahHeap::enter_evacuation() {
2859   _oom_evac_handler.enter_evacuation();
2860 }
2861 
2862 void ShenandoahHeap::leave_evacuation() {
2863   _oom_evac_handler.leave_evacuation();
2864 }
2865 
2866 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2867   _heap(ShenandoahHeap::heap()),
2868   _index(0) {}
2869 
2870 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2871   _heap(heap),
2872   _index(0) {}
2873 
2874 void ShenandoahRegionIterator::reset() {
2875   _index = 0;
2876 }
2877 
2878 bool ShenandoahRegionIterator::has_next() const {
2879   return _index < _heap->num_regions();
2880 }
2881 
2882 char ShenandoahHeap::gc_state() const {
2883   return _gc_state.raw_value();
2884 }
2885 
2886 void ShenandoahHeap::deduplicate_string(oop str) {
2887   assert(java_lang_String::is_instance(str), "invariant");
2888 
2889   if (ShenandoahStringDedup::is_enabled()) {
2890     ShenandoahStringDedup::deduplicate(str);
2891   }
2892 }
2893 
2894 const char* ShenandoahHeap::init_mark_event_message() const {
2895   bool update_refs = has_forwarded_objects();
2896   bool proc_refs = process_references();
2897   bool unload_cls = unload_classes();
2898 
2899   if (update_refs && proc_refs && unload_cls) {
2900     return "Pause Init Mark (update refs) (process weakrefs) (unload classes)";
2901   } else if (update_refs && proc_refs) {
2902     return "Pause Init Mark (update refs) (process weakrefs)";
2903   } else if (update_refs && unload_cls) {
2904     return "Pause Init Mark (update refs) (unload classes)";
2905   } else if (proc_refs && unload_cls) {
2906     return "Pause Init Mark (process weakrefs) (unload classes)";
2907   } else if (update_refs) {
2908     return "Pause Init Mark (update refs)";
2909   } else if (proc_refs) {
2910     return "Pause Init Mark (process weakrefs)";
2911   } else if (unload_cls) {
2912     return "Pause Init Mark (unload classes)";
2913   } else {
2914     return "Pause Init Mark";
2915   }
2916 }
2917 
2918 const char* ShenandoahHeap::final_mark_event_message() const {
2919   bool update_refs = has_forwarded_objects();
2920   bool proc_refs = process_references();
2921   bool unload_cls = unload_classes();
2922 
2923   if (update_refs && proc_refs && unload_cls) {
2924     return "Pause Final Mark (update refs) (process weakrefs) (unload classes)";
2925   } else if (update_refs && proc_refs) {
2926     return "Pause Final Mark (update refs) (process weakrefs)";
2927   } else if (update_refs && unload_cls) {
2928     return "Pause Final Mark (update refs) (unload classes)";
2929   } else if (proc_refs && unload_cls) {
2930     return "Pause Final Mark (process weakrefs) (unload classes)";
2931   } else if (update_refs) {
2932     return "Pause Final Mark (update refs)";
2933   } else if (proc_refs) {
2934     return "Pause Final Mark (process weakrefs)";
2935   } else if (unload_cls) {
2936     return "Pause Final Mark (unload classes)";
2937   } else {
2938     return "Pause Final Mark";
2939   }
2940 }
2941 
2942 const char* ShenandoahHeap::conc_mark_event_message() const {
2943   bool update_refs = has_forwarded_objects();
2944   bool proc_refs = process_references();
2945   bool unload_cls = unload_classes();
2946 
2947   if (update_refs && proc_refs && unload_cls) {
2948     return "Concurrent marking (update refs) (process weakrefs) (unload classes)";
2949   } else if (update_refs && proc_refs) {
2950     return "Concurrent marking (update refs) (process weakrefs)";
2951   } else if (update_refs && unload_cls) {
2952     return "Concurrent marking (update refs) (unload classes)";
2953   } else if (proc_refs && unload_cls) {
2954     return "Concurrent marking (process weakrefs) (unload classes)";
2955   } else if (update_refs) {
2956     return "Concurrent marking (update refs)";
2957   } else if (proc_refs) {
2958     return "Concurrent marking (process weakrefs)";
2959   } else if (unload_cls) {
2960     return "Concurrent marking (unload classes)";
2961   } else {
2962     return "Concurrent marking";
2963   }
2964 }
2965 
2966 const char* ShenandoahHeap::degen_event_message(ShenandoahDegenPoint point) const {
2967   switch (point) {
2968     case _degenerated_unset:
2969       return "Pause Degenerated GC (<UNSET>)";
2970     case _degenerated_traversal:
2971       return "Pause Degenerated GC (Traversal)";
2972     case _degenerated_outside_cycle:
2973       return "Pause Degenerated GC (Outside of Cycle)";
2974     case _degenerated_mark:
2975       return "Pause Degenerated GC (Mark)";
2976     case _degenerated_evac:
2977       return "Pause Degenerated GC (Evacuation)";
2978     case _degenerated_updaterefs:
2979       return "Pause Degenerated GC (Update Refs)";
2980     default:
2981       ShouldNotReachHere();
2982       return "ERROR";
2983   }
2984 }
2985 
2986 jushort* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2987 #ifdef ASSERT
2988   assert(_liveness_cache != NULL, "sanity");
2989   assert(worker_id < _max_workers, "sanity");
2990   for (uint i = 0; i < num_regions(); i++) {
2991     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2992   }
2993 #endif
2994   return _liveness_cache[worker_id];
2995 }
2996 
2997 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2998   assert(worker_id < _max_workers, "sanity");
2999   assert(_liveness_cache != NULL, "sanity");
3000   jushort* ld = _liveness_cache[worker_id];
3001   for (uint i = 0; i < num_regions(); i++) {
3002     ShenandoahHeapRegion* r = get_region(i);
3003     jushort live = ld[i];
3004     if (live > 0) {
3005       r->increase_live_data_gc_words(live);
3006       ld[i] = 0;
3007     }
3008   }
3009 }