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