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     {
1597       // jni_roots and weak_roots are OopStorage backed roots, concurrent iteration
1598       // may race against OopStorage::release() calls.
1599       ShenandoahEvacUpdateOopStorageRootsClosure cl;
1600       _jni_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl);
1601       _weak_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl);
1602     }
1603 
1604     {
1605       ShenandoahEvacuateUpdateRootsClosure cl;
1606       CLDToOopClosure clds(&cl, ClassLoaderData::_claim_strong);
1607       _cld_roots.cld_do(&clds);
1608     }
1609   }
1610 };
1611 
1612 void ShenandoahHeap::op_roots() {
1613   if (is_evacuation_in_progress() &&
1614       ShenandoahConcurrentRoots::should_do_concurrent_roots()) {
1615     ShenandoahConcurrentRootsEvacUpdateTask task;
1616     workers()->run_task(&task);
1617   }
1618 }
1619 
1620 void ShenandoahHeap::op_reset() {
1621   reset_mark_bitmap();
1622 }
1623 
1624 void ShenandoahHeap::op_preclean() {
1625   concurrent_mark()->preclean_weak_refs();
1626 }
1627 
1628 void ShenandoahHeap::op_init_traversal() {
1629   traversal_gc()->init_traversal_collection();
1630 }
1631 
1632 void ShenandoahHeap::op_traversal() {
1633   traversal_gc()->concurrent_traversal_collection();
1634 }
1635 
1636 void ShenandoahHeap::op_final_traversal() {
1637   traversal_gc()->final_traversal_collection();
1638 }
1639 
1640 void ShenandoahHeap::op_full(GCCause::Cause cause) {
1641   ShenandoahMetricsSnapshot metrics;
1642   metrics.snap_before();
1643 
1644   full_gc()->do_it(cause);
1645   if (UseTLAB) {
1646     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_resize_tlabs);
1647     resize_all_tlabs();
1648   }
1649 
1650   metrics.snap_after();
1651 
1652   if (metrics.is_good_progress()) {
1653     _progress_last_gc.set();
1654   } else {
1655     // Nothing to do. Tell the allocation path that we have failed to make
1656     // progress, and it can finally fail.
1657     _progress_last_gc.unset();
1658   }
1659 }
1660 
1661 void ShenandoahHeap::op_degenerated(ShenandoahDegenPoint point) {
1662   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
1663   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
1664   // some phase, we have to upgrade the Degenerate GC to Full GC.
1665 
1666   clear_cancelled_gc();
1667 
1668   ShenandoahMetricsSnapshot metrics;
1669   metrics.snap_before();
1670 
1671   switch (point) {
1672     case _degenerated_traversal:
1673       {
1674         // Drop the collection set. Note: this leaves some already forwarded objects
1675         // behind, which may be problematic, see comments for ShenandoahEvacAssist
1676         // workarounds in ShenandoahTraversalHeuristics.
1677 
1678         ShenandoahHeapLocker locker(lock());
1679         collection_set()->clear_current_index();
1680         for (size_t i = 0; i < collection_set()->count(); i++) {
1681           ShenandoahHeapRegion* r = collection_set()->next();
1682           r->make_regular_bypass();
1683         }
1684         collection_set()->clear();
1685       }
1686       op_final_traversal();
1687       op_cleanup();
1688       return;
1689 
1690     // The cases below form the Duff's-like device: it describes the actual GC cycle,
1691     // but enters it at different points, depending on which concurrent phase had
1692     // degenerated.
1693 
1694     case _degenerated_outside_cycle:
1695       // We have degenerated from outside the cycle, which means something is bad with
1696       // the heap, most probably heavy humongous fragmentation, or we are very low on free
1697       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
1698       // we can do the most aggressive degen cycle, which includes processing references and
1699       // class unloading, unless those features are explicitly disabled.
1700       //
1701       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
1702       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
1703       set_process_references(heuristics()->can_process_references());
1704       set_unload_classes(heuristics()->can_unload_classes());
1705 
1706       if (is_traversal_mode()) {
1707         // Not possible to degenerate from here, upgrade to Full GC right away.
1708         cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1709         op_degenerated_fail();
1710         return;
1711       }
1712 
1713       op_reset();
1714 
1715       op_init_mark();
1716       if (cancelled_gc()) {
1717         op_degenerated_fail();
1718         return;
1719       }
1720 
1721     case _degenerated_mark:
1722       op_final_mark();
1723       if (cancelled_gc()) {
1724         op_degenerated_fail();
1725         return;
1726       }
1727 
1728       op_cleanup();
1729 
1730     case _degenerated_evac:
1731       // If heuristics thinks we should do the cycle, this flag would be set,
1732       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
1733       if (is_evacuation_in_progress()) {
1734 
1735         // Degeneration under oom-evac protocol might have left some objects in
1736         // collection set un-evacuated. Restart evacuation from the beginning to
1737         // capture all objects. For all the objects that are already evacuated,
1738         // it would be a simple check, which is supposed to be fast. This is also
1739         // safe to do even without degeneration, as CSet iterator is at beginning
1740         // in preparation for evacuation anyway.
1741         //
1742         // Before doing that, we need to make sure we never had any cset-pinned
1743         // regions. This may happen if allocation failure happened when evacuating
1744         // the about-to-be-pinned object, oom-evac protocol left the object in
1745         // the collection set, and then the pin reached the cset region. If we continue
1746         // the cycle here, we would trash the cset and alive objects in it. To avoid
1747         // it, we fail degeneration right away and slide into Full GC to recover.
1748 
1749         {
1750           collection_set()->clear_current_index();
1751 
1752           ShenandoahHeapRegion* r;
1753           while ((r = collection_set()->next()) != NULL) {
1754             if (r->is_pinned()) {
1755               cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1756               op_degenerated_fail();
1757               return;
1758             }
1759           }
1760 
1761           collection_set()->clear_current_index();
1762         }
1763 
1764         op_stw_evac();
1765         if (cancelled_gc()) {
1766           op_degenerated_fail();
1767           return;
1768         }
1769       }
1770 
1771       // If heuristics thinks we should do the cycle, this flag would be set,
1772       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
1773       if (has_forwarded_objects()) {
1774         op_init_updaterefs();
1775         if (cancelled_gc()) {
1776           op_degenerated_fail();
1777           return;
1778         }
1779       }
1780 
1781     case _degenerated_updaterefs:
1782       if (has_forwarded_objects()) {
1783         op_final_updaterefs();
1784         if (cancelled_gc()) {
1785           op_degenerated_fail();
1786           return;
1787         }
1788       }
1789 
1790       op_cleanup();
1791       break;
1792 
1793     default:
1794       ShouldNotReachHere();
1795   }
1796 
1797   if (ShenandoahVerify) {
1798     verifier()->verify_after_degenerated();
1799   }
1800 
1801   if (VerifyAfterGC) {
1802     Universe::verify();
1803   }
1804 
1805   metrics.snap_after();
1806 
1807   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
1808   // because that probably means the heap is overloaded and/or fragmented.
1809   if (!metrics.is_good_progress()) {
1810     _progress_last_gc.unset();
1811     cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1812     op_degenerated_futile();
1813   } else {
1814     _progress_last_gc.set();
1815   }
1816 }
1817 
1818 void ShenandoahHeap::op_degenerated_fail() {
1819   log_info(gc)("Cannot finish degeneration, upgrading to Full GC");
1820   shenandoah_policy()->record_degenerated_upgrade_to_full();
1821   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1822 }
1823 
1824 void ShenandoahHeap::op_degenerated_futile() {
1825   shenandoah_policy()->record_degenerated_upgrade_to_full();
1826   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1827 }
1828 
1829 void ShenandoahHeap::stop_concurrent_marking() {
1830   assert(is_concurrent_mark_in_progress(), "How else could we get here?");
1831   set_concurrent_mark_in_progress(false);
1832   if (!cancelled_gc()) {
1833     // If we needed to update refs, and concurrent marking has been cancelled,
1834     // we need to finish updating references.
1835     set_has_forwarded_objects(false);
1836     mark_complete_marking_context();
1837   }
1838 }
1839 
1840 void ShenandoahHeap::force_satb_flush_all_threads() {
1841   if (!is_concurrent_mark_in_progress() && !is_concurrent_traversal_in_progress()) {
1842     // No need to flush SATBs
1843     return;
1844   }
1845 
1846   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1847     ShenandoahThreadLocalData::set_force_satb_flush(t, true);
1848   }
1849   // The threads are not "acquiring" their thread-local data, but it does not
1850   // hurt to "release" the updates here anyway.
1851   OrderAccess::fence();
1852 }
1853 
1854 void ShenandoahHeap::set_gc_state_all_threads(char state) {
1855   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1856     ShenandoahThreadLocalData::set_gc_state(t, state);
1857   }
1858 }
1859 
1860 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1861   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1862   _gc_state.set_cond(mask, value);
1863   set_gc_state_all_threads(_gc_state.raw_value());
1864 }
1865 
1866 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1867   if (has_forwarded_objects()) {
1868     set_gc_state_mask(MARKING | UPDATEREFS, in_progress);
1869   } else {
1870     set_gc_state_mask(MARKING, in_progress);
1871   }
1872   ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1873 }
1874 
1875 void ShenandoahHeap::set_concurrent_traversal_in_progress(bool in_progress) {
1876    set_gc_state_mask(TRAVERSAL | HAS_FORWARDED | UPDATEREFS, in_progress);
1877    ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1878 }
1879 
1880 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1881   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1882   set_gc_state_mask(EVACUATION, in_progress);
1883 }
1884 
1885 void ShenandoahHeap::ref_processing_init() {
1886   assert(_max_workers > 0, "Sanity");
1887 
1888   _ref_processor =
1889     new ReferenceProcessor(&_subject_to_discovery,  // is_subject_to_discovery
1890                            ParallelRefProcEnabled,  // MT processing
1891                            _max_workers,            // Degree of MT processing
1892                            true,                    // MT discovery
1893                            _max_workers,            // Degree of MT discovery
1894                            false,                   // Reference discovery is not atomic
1895                            NULL,                    // No closure, should be installed before use
1896                            true);                   // Scale worker threads
1897 
1898   shenandoah_assert_rp_isalive_not_installed();
1899 }
1900 
1901 GCTracer* ShenandoahHeap::tracer() {
1902   return shenandoah_policy()->tracer();
1903 }
1904 
1905 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1906   return _free_set->used();
1907 }
1908 
1909 bool ShenandoahHeap::try_cancel_gc() {
1910   while (true) {
1911     jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
1912     if (prev == CANCELLABLE) return true;
1913     else if (prev == CANCELLED) return false;
1914     assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers");
1915     assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED");
1916     {
1917       // We need to provide a safepoint here, otherwise we might
1918       // spin forever if a SP is pending.
1919       ThreadBlockInVM sp(JavaThread::current());
1920       SpinPause();
1921     }
1922   }
1923 }
1924 
1925 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1926   if (try_cancel_gc()) {
1927     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1928     log_info(gc)("%s", msg.buffer());
1929     Events::log(Thread::current(), "%s", msg.buffer());
1930   }
1931 }
1932 
1933 uint ShenandoahHeap::max_workers() {
1934   return _max_workers;
1935 }
1936 
1937 void ShenandoahHeap::stop() {
1938   // The shutdown sequence should be able to terminate when GC is running.
1939 
1940   // Step 0. Notify policy to disable event recording.
1941   _shenandoah_policy->record_shutdown();
1942 
1943   // Step 1. Notify control thread that we are in shutdown.
1944   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1945   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1946   control_thread()->prepare_for_graceful_shutdown();
1947 
1948   // Step 2. Notify GC workers that we are cancelling GC.
1949   cancel_gc(GCCause::_shenandoah_stop_vm);
1950 
1951   // Step 3. Wait until GC worker exits normally.
1952   control_thread()->stop();
1953 
1954   // Step 4. Stop String Dedup thread if it is active
1955   if (ShenandoahStringDedup::is_enabled()) {
1956     ShenandoahStringDedup::stop();
1957   }
1958 }
1959 
1960 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
1961   if (!unload_classes()) return;
1962   bool purged_class;
1963 
1964   // Unload classes and purge SystemDictionary.
1965   {
1966     ShenandoahGCPhase phase(full_gc ?
1967                             ShenandoahPhaseTimings::full_gc_purge_class_unload :
1968                             ShenandoahPhaseTimings::purge_class_unload);
1969     purged_class = SystemDictionary::do_unloading(gc_timer());
1970   }
1971 
1972   {
1973     ShenandoahGCPhase phase(full_gc ?
1974                             ShenandoahPhaseTimings::full_gc_purge_par :
1975                             ShenandoahPhaseTimings::purge_par);
1976     ShenandoahIsAliveSelector is_alive;
1977     uint num_workers = _workers->active_workers();
1978     ShenandoahClassUnloadingTask unlink_task(is_alive.is_alive_closure(), num_workers, purged_class);
1979     _workers->run_task(&unlink_task);
1980   }
1981 
1982   {
1983     ShenandoahGCPhase phase(full_gc ?
1984                             ShenandoahPhaseTimings::full_gc_purge_cldg :
1985                             ShenandoahPhaseTimings::purge_cldg);
1986     ClassLoaderDataGraph::purge();
1987   }
1988   // Resize and verify metaspace
1989   MetaspaceGC::compute_new_size();
1990   MetaspaceUtils::verify_metrics();
1991 }
1992 
1993 // Process leftover weak oops: update them, if needed or assert they do not
1994 // need updating otherwise.
1995 // Weak processor API requires us to visit the oops, even if we are not doing
1996 // anything to them.
1997 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
1998   ShenandoahGCPhase root_phase(full_gc ?
1999                                ShenandoahPhaseTimings::full_gc_purge :
2000                                ShenandoahPhaseTimings::purge);
2001   uint num_workers = _workers->active_workers();
2002   ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
2003                                                ShenandoahPhaseTimings::full_gc_purge_par :
2004                                                ShenandoahPhaseTimings::purge_par;
2005   // Cleanup weak roots
2006   ShenandoahGCPhase phase(timing_phase);
2007   if (has_forwarded_objects()) {
2008     ShenandoahForwardedIsAliveClosure is_alive;
2009     ShenandoahUpdateRefsClosure keep_alive;
2010     ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure>
2011       cleaning_task(&is_alive, &keep_alive, num_workers);
2012     _workers->run_task(&cleaning_task);
2013   } else {
2014     ShenandoahIsAliveClosure is_alive;
2015 #ifdef ASSERT
2016   ShenandoahAssertNotForwardedClosure verify_cl;
2017   ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
2018     cleaning_task(&is_alive, &verify_cl, num_workers);
2019 #else
2020   ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
2021     cleaning_task(&is_alive, &do_nothing_cl, num_workers);
2022 #endif
2023     _workers->run_task(&cleaning_task);
2024   }
2025 }
2026 
2027 void ShenandoahHeap::parallel_cleaning(bool full_gc) {
2028   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2029   stw_process_weak_roots(full_gc);
2030   stw_unload_classes(full_gc);
2031 }
2032 
2033 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
2034   set_gc_state_mask(HAS_FORWARDED, cond);
2035 }
2036 
2037 void ShenandoahHeap::set_process_references(bool pr) {
2038   _process_references.set_cond(pr);
2039 }
2040 
2041 void ShenandoahHeap::set_unload_classes(bool uc) {
2042   _unload_classes.set_cond(uc);
2043 }
2044 
2045 bool ShenandoahHeap::process_references() const {
2046   return _process_references.is_set();
2047 }
2048 
2049 bool ShenandoahHeap::unload_classes() const {
2050   return _unload_classes.is_set();
2051 }
2052 
2053 address ShenandoahHeap::in_cset_fast_test_addr() {
2054   ShenandoahHeap* heap = ShenandoahHeap::heap();
2055   assert(heap->collection_set() != NULL, "Sanity");
2056   return (address) heap->collection_set()->biased_map_address();
2057 }
2058 
2059 address ShenandoahHeap::cancelled_gc_addr() {
2060   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
2061 }
2062 
2063 address ShenandoahHeap::gc_state_addr() {
2064   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
2065 }
2066 
2067 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
2068   return OrderAccess::load_acquire(&_bytes_allocated_since_gc_start);
2069 }
2070 
2071 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
2072   OrderAccess::release_store_fence(&_bytes_allocated_since_gc_start, (size_t)0);
2073 }
2074 
2075 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2076   _degenerated_gc_in_progress.set_cond(in_progress);
2077 }
2078 
2079 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2080   _full_gc_in_progress.set_cond(in_progress);
2081 }
2082 
2083 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2084   assert (is_full_gc_in_progress(), "should be");
2085   _full_gc_move_in_progress.set_cond(in_progress);
2086 }
2087 
2088 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2089   set_gc_state_mask(UPDATEREFS, in_progress);
2090 }
2091 
2092 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2093   ShenandoahCodeRoots::add_nmethod(nm);
2094 }
2095 
2096 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2097   ShenandoahCodeRoots::remove_nmethod(nm);
2098 }
2099 
2100 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2101   ShenandoahHeapLocker locker(lock());
2102   heap_region_containing(o)->make_pinned();
2103   return o;
2104 }
2105 
2106 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2107   ShenandoahHeapLocker locker(lock());
2108   heap_region_containing(o)->make_unpinned();
2109 }
2110 
2111 GCTimer* ShenandoahHeap::gc_timer() const {
2112   return _gc_timer;
2113 }
2114 
2115 #ifdef ASSERT
2116 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2117   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2118 
2119   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2120     if (UseDynamicNumberOfGCThreads ||
2121         (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) {
2122       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
2123     } else {
2124       // Use ParallelGCThreads inside safepoints
2125       assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints");
2126     }
2127   } else {
2128     if (UseDynamicNumberOfGCThreads ||
2129         (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) {
2130       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
2131     } else {
2132       // Use ConcGCThreads outside safepoints
2133       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2134     }
2135   }
2136 }
2137 #endif
2138 
2139 ShenandoahVerifier* ShenandoahHeap::verifier() {
2140   guarantee(ShenandoahVerify, "Should be enabled");
2141   assert (_verifier != NULL, "sanity");
2142   return _verifier;
2143 }
2144 
2145 template<class T>
2146 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
2147 private:
2148   T cl;
2149   ShenandoahHeap* _heap;
2150   ShenandoahRegionIterator* _regions;
2151   bool _concurrent;
2152 public:
2153   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions, bool concurrent) :
2154     AbstractGangTask("Concurrent Update References Task"),
2155     cl(T()),
2156     _heap(ShenandoahHeap::heap()),
2157     _regions(regions),
2158     _concurrent(concurrent) {
2159   }
2160 
2161   void work(uint worker_id) {
2162     if (_concurrent) {
2163       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2164       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2165       do_work();
2166     } else {
2167       ShenandoahParallelWorkerSession worker_session(worker_id);
2168       do_work();
2169     }
2170   }
2171 
2172 private:
2173   void do_work() {
2174     ShenandoahHeapRegion* r = _regions->next();
2175     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2176     while (r != NULL) {
2177       HeapWord* top_at_start_ur = r->concurrent_iteration_safe_limit();
2178       assert (top_at_start_ur >= r->bottom(), "sanity");
2179       if (r->is_active() && !r->is_cset()) {
2180         _heap->marked_object_oop_iterate(r, &cl, top_at_start_ur);
2181       }
2182       if (ShenandoahPacing) {
2183         _heap->pacer()->report_updaterefs(pointer_delta(top_at_start_ur, r->bottom()));
2184       }
2185       if (_heap->check_cancelled_gc_and_yield(_concurrent)) {
2186         return;
2187       }
2188       r = _regions->next();
2189     }
2190   }
2191 };
2192 
2193 void ShenandoahHeap::update_heap_references(bool concurrent) {
2194   ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsClosure> task(&_update_refs_iterator, concurrent);
2195   workers()->run_task(&task);
2196 }
2197 
2198 void ShenandoahHeap::op_init_updaterefs() {
2199   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2200 
2201   set_evacuation_in_progress(false);
2202 
2203   retire_and_reset_gclabs();
2204 
2205   if (ShenandoahVerify) {
2206     if (!is_degenerated_gc_in_progress()) {
2207       verifier()->verify_roots_no_forwarded_except(ShenandoahRootVerifier::ThreadRoots);
2208     }
2209     verifier()->verify_before_updaterefs();
2210   }
2211 
2212   set_update_refs_in_progress(true);
2213   make_parsable(true);
2214   for (uint i = 0; i < num_regions(); i++) {
2215     ShenandoahHeapRegion* r = get_region(i);
2216     r->set_concurrent_iteration_safe_limit(r->top());
2217   }
2218 
2219   // Reset iterator.
2220   _update_refs_iterator.reset();
2221 
2222   if (ShenandoahPacing) {
2223     pacer()->setup_for_updaterefs();
2224   }
2225 }
2226 
2227 void ShenandoahHeap::op_final_updaterefs() {
2228   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2229 
2230   // Check if there is left-over work, and finish it
2231   if (_update_refs_iterator.has_next()) {
2232     ShenandoahGCPhase final_work(ShenandoahPhaseTimings::final_update_refs_finish_work);
2233 
2234     // Finish updating references where we left off.
2235     clear_cancelled_gc();
2236     update_heap_references(false);
2237   }
2238 
2239   // Clear cancelled GC, if set. On cancellation path, the block before would handle
2240   // everything. On degenerated paths, cancelled gc would not be set anyway.
2241   if (cancelled_gc()) {
2242     clear_cancelled_gc();
2243   }
2244   assert(!cancelled_gc(), "Should have been done right before");
2245 
2246   if (ShenandoahVerify && !is_degenerated_gc_in_progress()) {
2247     verifier()->verify_roots_no_forwarded_except(ShenandoahRootVerifier::ThreadRoots);
2248   }
2249 
2250   if (is_degenerated_gc_in_progress()) {
2251     concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots);
2252   } else {
2253     concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::final_update_refs_roots);
2254   }
2255 
2256   // Has to be done before cset is clear
2257   if (ShenandoahVerify) {
2258     verifier()->verify_roots_in_to_space();
2259   }
2260 
2261   ShenandoahGCPhase final_update_refs(ShenandoahPhaseTimings::final_update_refs_recycle);
2262 
2263   trash_cset_regions();
2264   set_has_forwarded_objects(false);
2265   set_update_refs_in_progress(false);
2266 
2267   if (ShenandoahVerify) {
2268     verifier()->verify_after_updaterefs();
2269   }
2270 
2271   if (VerifyAfterGC) {
2272     Universe::verify();
2273   }
2274 
2275   {
2276     ShenandoahHeapLocker locker(lock());
2277     _free_set->rebuild();
2278   }
2279 }
2280 
2281 #ifdef ASSERT
2282 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() {
2283   _lock.assert_owned_by_current_thread();
2284 }
2285 
2286 void ShenandoahHeap::assert_heaplock_not_owned_by_current_thread() {
2287   _lock.assert_not_owned_by_current_thread();
2288 }
2289 
2290 void ShenandoahHeap::assert_heaplock_or_safepoint() {
2291   _lock.assert_owned_by_current_thread_or_safepoint();
2292 }
2293 #endif
2294 
2295 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2296   print_on(st);
2297   print_heap_regions_on(st);
2298 }
2299 
2300 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2301   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2302 
2303   size_t regions_from = _bitmap_regions_per_slice * slice;
2304   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2305   for (size_t g = regions_from; g < regions_to; g++) {
2306     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2307     if (skip_self && g == r->region_number()) continue;
2308     if (get_region(g)->is_committed()) {
2309       return true;
2310     }
2311   }
2312   return false;
2313 }
2314 
2315 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2316   assert_heaplock_owned_by_current_thread();
2317 
2318   // Bitmaps in special regions do not need commits
2319   if (_bitmap_region_special) {
2320     return true;
2321   }
2322 
2323   if (is_bitmap_slice_committed(r, true)) {
2324     // Some other region from the group is already committed, meaning the bitmap
2325     // slice is already committed, we exit right away.
2326     return true;
2327   }
2328 
2329   // Commit the bitmap slice:
2330   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2331   size_t off = _bitmap_bytes_per_slice * slice;
2332   size_t len = _bitmap_bytes_per_slice;
2333   if (!os::commit_memory((char*)_bitmap_region.start() + off, len, false)) {
2334     return false;
2335   }
2336   return true;
2337 }
2338 
2339 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2340   assert_heaplock_owned_by_current_thread();
2341 
2342   // Bitmaps in special regions do not need uncommits
2343   if (_bitmap_region_special) {
2344     return true;
2345   }
2346 
2347   if (is_bitmap_slice_committed(r, true)) {
2348     // Some other region from the group is still committed, meaning the bitmap
2349     // slice is should stay committed, exit right away.
2350     return true;
2351   }
2352 
2353   // Uncommit the bitmap slice:
2354   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2355   size_t off = _bitmap_bytes_per_slice * slice;
2356   size_t len = _bitmap_bytes_per_slice;
2357   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2358     return false;
2359   }
2360   return true;
2361 }
2362 
2363 void ShenandoahHeap::safepoint_synchronize_begin() {
2364   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2365     SuspendibleThreadSet::synchronize();
2366   }
2367 }
2368 
2369 void ShenandoahHeap::safepoint_synchronize_end() {
2370   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2371     SuspendibleThreadSet::desynchronize();
2372   }
2373 }
2374 
2375 void ShenandoahHeap::vmop_entry_init_mark() {
2376   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2377   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2378   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark_gross);
2379 
2380   try_inject_alloc_failure();
2381   VM_ShenandoahInitMark op;
2382   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
2383 }
2384 
2385 void ShenandoahHeap::vmop_entry_final_mark() {
2386   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2387   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2388   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark_gross);
2389 
2390   try_inject_alloc_failure();
2391   VM_ShenandoahFinalMarkStartEvac op;
2392   VMThread::execute(&op); // jump to entry_final_mark under safepoint
2393 }
2394 
2395 void ShenandoahHeap::vmop_entry_final_evac() {
2396   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2397   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2398   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_gross);
2399 
2400   VM_ShenandoahFinalEvac op;
2401   VMThread::execute(&op); // jump to entry_final_evac under safepoint
2402 }
2403 
2404 void ShenandoahHeap::vmop_entry_init_updaterefs() {
2405   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2406   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2407   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_gross);
2408 
2409   try_inject_alloc_failure();
2410   VM_ShenandoahInitUpdateRefs op;
2411   VMThread::execute(&op);
2412 }
2413 
2414 void ShenandoahHeap::vmop_entry_final_updaterefs() {
2415   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2416   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2417   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_gross);
2418 
2419   try_inject_alloc_failure();
2420   VM_ShenandoahFinalUpdateRefs op;
2421   VMThread::execute(&op);
2422 }
2423 
2424 void ShenandoahHeap::vmop_entry_init_traversal() {
2425   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2426   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2427   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc_gross);
2428 
2429   try_inject_alloc_failure();
2430   VM_ShenandoahInitTraversalGC op;
2431   VMThread::execute(&op);
2432 }
2433 
2434 void ShenandoahHeap::vmop_entry_final_traversal() {
2435   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2436   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2437   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc_gross);
2438 
2439   try_inject_alloc_failure();
2440   VM_ShenandoahFinalTraversalGC op;
2441   VMThread::execute(&op);
2442 }
2443 
2444 void ShenandoahHeap::vmop_entry_full(GCCause::Cause cause) {
2445   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2446   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2447   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_gross);
2448 
2449   try_inject_alloc_failure();
2450   VM_ShenandoahFullGC op(cause);
2451   VMThread::execute(&op);
2452 }
2453 
2454 void ShenandoahHeap::vmop_degenerated(ShenandoahDegenPoint point) {
2455   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2456   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2457   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_gross);
2458 
2459   VM_ShenandoahDegeneratedGC degenerated_gc((int)point);
2460   VMThread::execute(&degenerated_gc);
2461 }
2462 
2463 void ShenandoahHeap::entry_init_mark() {
2464   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2465   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark);
2466   const char* msg = init_mark_event_message();
2467   GCTraceTime(Info, gc) time(msg, gc_timer());
2468   EventMark em("%s", msg);
2469 
2470   ShenandoahWorkerScope scope(workers(),
2471                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
2472                               "init marking");
2473 
2474   op_init_mark();
2475 }
2476 
2477 void ShenandoahHeap::entry_final_mark() {
2478   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2479   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark);
2480   const char* msg = final_mark_event_message();
2481   GCTraceTime(Info, gc) time(msg, gc_timer());
2482   EventMark em("%s", msg);
2483 
2484   ShenandoahWorkerScope scope(workers(),
2485                               ShenandoahWorkerPolicy::calc_workers_for_final_marking(),
2486                               "final marking");
2487 
2488   op_final_mark();
2489 }
2490 
2491 void ShenandoahHeap::entry_final_evac() {
2492   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2493   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac);
2494   static const char* msg = "Pause Final Evac";
2495   GCTraceTime(Info, gc) time(msg, gc_timer());
2496   EventMark em("%s", msg);
2497 
2498   op_final_evac();
2499 }
2500 
2501 void ShenandoahHeap::entry_init_updaterefs() {
2502   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2503   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs);
2504 
2505   static const char* msg = "Pause Init Update Refs";
2506   GCTraceTime(Info, gc) time(msg, gc_timer());
2507   EventMark em("%s", msg);
2508 
2509   // No workers used in this phase, no setup required
2510 
2511   op_init_updaterefs();
2512 }
2513 
2514 void ShenandoahHeap::entry_final_updaterefs() {
2515   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2516   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs);
2517 
2518   static const char* msg = "Pause Final Update Refs";
2519   GCTraceTime(Info, gc) time(msg, gc_timer());
2520   EventMark em("%s", msg);
2521 
2522   ShenandoahWorkerScope scope(workers(),
2523                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
2524                               "final reference update");
2525 
2526   op_final_updaterefs();
2527 }
2528 
2529 void ShenandoahHeap::entry_init_traversal() {
2530   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2531   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc);
2532 
2533   static const char* msg = "Pause Init Traversal";
2534   GCTraceTime(Info, gc) time(msg, gc_timer());
2535   EventMark em("%s", msg);
2536 
2537   ShenandoahWorkerScope scope(workers(),
2538                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2539                               "init traversal");
2540 
2541   op_init_traversal();
2542 }
2543 
2544 void ShenandoahHeap::entry_final_traversal() {
2545   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2546   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc);
2547 
2548   static const char* msg = "Pause Final Traversal";
2549   GCTraceTime(Info, gc) time(msg, gc_timer());
2550   EventMark em("%s", msg);
2551 
2552   ShenandoahWorkerScope scope(workers(),
2553                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2554                               "final traversal");
2555 
2556   op_final_traversal();
2557 }
2558 
2559 void ShenandoahHeap::entry_full(GCCause::Cause cause) {
2560   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2561   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc);
2562 
2563   static const char* msg = "Pause Full";
2564   GCTraceTime(Info, gc) time(msg, gc_timer(), cause, true);
2565   EventMark em("%s", msg);
2566 
2567   ShenandoahWorkerScope scope(workers(),
2568                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
2569                               "full gc");
2570 
2571   op_full(cause);
2572 }
2573 
2574 void ShenandoahHeap::entry_degenerated(int point) {
2575   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2576   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc);
2577 
2578   ShenandoahDegenPoint dpoint = (ShenandoahDegenPoint)point;
2579   const char* msg = degen_event_message(dpoint);
2580   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2581   EventMark em("%s", msg);
2582 
2583   ShenandoahWorkerScope scope(workers(),
2584                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
2585                               "stw degenerated gc");
2586 
2587   set_degenerated_gc_in_progress(true);
2588   op_degenerated(dpoint);
2589   set_degenerated_gc_in_progress(false);
2590 }
2591 
2592 void ShenandoahHeap::entry_mark() {
2593   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2594 
2595   const char* msg = conc_mark_event_message();
2596   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2597   EventMark em("%s", msg);
2598 
2599   ShenandoahWorkerScope scope(workers(),
2600                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
2601                               "concurrent marking");
2602 
2603   try_inject_alloc_failure();
2604   op_mark();
2605 }
2606 
2607 void ShenandoahHeap::entry_evac() {
2608   ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac);
2609   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2610 
2611   static const char* msg = "Concurrent evacuation";
2612   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2613   EventMark em("%s", msg);
2614 
2615   ShenandoahWorkerScope scope(workers(),
2616                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
2617                               "concurrent evacuation");
2618 
2619   try_inject_alloc_failure();
2620   op_conc_evac();
2621 }
2622 
2623 void ShenandoahHeap::entry_updaterefs() {
2624   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs);
2625 
2626   static const char* msg = "Concurrent update references";
2627   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2628   EventMark em("%s", msg);
2629 
2630   ShenandoahWorkerScope scope(workers(),
2631                               ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(),
2632                               "concurrent reference update");
2633 
2634   try_inject_alloc_failure();
2635   op_updaterefs();
2636 }
2637 
2638 void ShenandoahHeap::entry_roots() {
2639   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_roots);
2640 
2641   static const char* msg = "Concurrent roots processing";
2642   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2643   EventMark em("%s", msg);
2644 
2645   ShenandoahWorkerScope scope(workers(),
2646                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
2647                               "concurrent root processing");
2648 
2649   try_inject_alloc_failure();
2650   op_roots();
2651 }
2652 
2653 void ShenandoahHeap::entry_cleanup() {
2654   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup);
2655 
2656   static const char* msg = "Concurrent cleanup";
2657   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2658   EventMark em("%s", msg);
2659 
2660   // This phase does not use workers, no need for setup
2661 
2662   try_inject_alloc_failure();
2663   op_cleanup();
2664 }
2665 
2666 void ShenandoahHeap::entry_reset() {
2667   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_reset);
2668 
2669   static const char* msg = "Concurrent reset";
2670   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2671   EventMark em("%s", msg);
2672 
2673   ShenandoahWorkerScope scope(workers(),
2674                               ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
2675                               "concurrent reset");
2676 
2677   try_inject_alloc_failure();
2678   op_reset();
2679 }
2680 
2681 void ShenandoahHeap::entry_preclean() {
2682   if (ShenandoahPreclean && process_references()) {
2683     static const char* msg = "Concurrent precleaning";
2684     GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2685     EventMark em("%s", msg);
2686 
2687     ShenandoahGCPhase conc_preclean(ShenandoahPhaseTimings::conc_preclean);
2688 
2689     ShenandoahWorkerScope scope(workers(),
2690                                 ShenandoahWorkerPolicy::calc_workers_for_conc_preclean(),
2691                                 "concurrent preclean",
2692                                 /* check_workers = */ false);
2693 
2694     try_inject_alloc_failure();
2695     op_preclean();
2696   }
2697 }
2698 
2699 void ShenandoahHeap::entry_traversal() {
2700   static const char* msg = "Concurrent traversal";
2701   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2702   EventMark em("%s", msg);
2703 
2704   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2705 
2706   ShenandoahWorkerScope scope(workers(),
2707                               ShenandoahWorkerPolicy::calc_workers_for_conc_traversal(),
2708                               "concurrent traversal");
2709 
2710   try_inject_alloc_failure();
2711   op_traversal();
2712 }
2713 
2714 void ShenandoahHeap::entry_uncommit(double shrink_before) {
2715   static const char *msg = "Concurrent uncommit";
2716   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2717   EventMark em("%s", msg);
2718 
2719   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_uncommit);
2720 
2721   op_uncommit(shrink_before);
2722 }
2723 
2724 void ShenandoahHeap::try_inject_alloc_failure() {
2725   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2726     _inject_alloc_failure.set();
2727     os::naked_short_sleep(1);
2728     if (cancelled_gc()) {
2729       log_info(gc)("Allocation failure was successfully injected");
2730     }
2731   }
2732 }
2733 
2734 bool ShenandoahHeap::should_inject_alloc_failure() {
2735   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2736 }
2737 
2738 void ShenandoahHeap::initialize_serviceability() {
2739   _memory_pool = new ShenandoahMemoryPool(this);
2740   _cycle_memory_manager.add_pool(_memory_pool);
2741   _stw_memory_manager.add_pool(_memory_pool);
2742 }
2743 
2744 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2745   GrowableArray<GCMemoryManager*> memory_managers(2);
2746   memory_managers.append(&_cycle_memory_manager);
2747   memory_managers.append(&_stw_memory_manager);
2748   return memory_managers;
2749 }
2750 
2751 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2752   GrowableArray<MemoryPool*> memory_pools(1);
2753   memory_pools.append(_memory_pool);
2754   return memory_pools;
2755 }
2756 
2757 MemoryUsage ShenandoahHeap::memory_usage() {
2758   return _memory_pool->get_memory_usage();
2759 }
2760 
2761 void ShenandoahHeap::enter_evacuation() {
2762   _oom_evac_handler.enter_evacuation();
2763 }
2764 
2765 void ShenandoahHeap::leave_evacuation() {
2766   _oom_evac_handler.leave_evacuation();
2767 }
2768 
2769 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2770   _heap(ShenandoahHeap::heap()),
2771   _index(0) {}
2772 
2773 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2774   _heap(heap),
2775   _index(0) {}
2776 
2777 void ShenandoahRegionIterator::reset() {
2778   _index = 0;
2779 }
2780 
2781 bool ShenandoahRegionIterator::has_next() const {
2782   return _index < _heap->num_regions();
2783 }
2784 
2785 char ShenandoahHeap::gc_state() const {
2786   return _gc_state.raw_value();
2787 }
2788 
2789 void ShenandoahHeap::deduplicate_string(oop str) {
2790   assert(java_lang_String::is_instance(str), "invariant");
2791 
2792   if (ShenandoahStringDedup::is_enabled()) {
2793     ShenandoahStringDedup::deduplicate(str);
2794   }
2795 }
2796 
2797 const char* ShenandoahHeap::init_mark_event_message() const {
2798   bool update_refs = has_forwarded_objects();
2799   bool proc_refs = process_references();
2800   bool unload_cls = unload_classes();
2801 
2802   if (update_refs && proc_refs && unload_cls) {
2803     return "Pause Init Mark (update refs) (process weakrefs) (unload classes)";
2804   } else if (update_refs && proc_refs) {
2805     return "Pause Init Mark (update refs) (process weakrefs)";
2806   } else if (update_refs && unload_cls) {
2807     return "Pause Init Mark (update refs) (unload classes)";
2808   } else if (proc_refs && unload_cls) {
2809     return "Pause Init Mark (process weakrefs) (unload classes)";
2810   } else if (update_refs) {
2811     return "Pause Init Mark (update refs)";
2812   } else if (proc_refs) {
2813     return "Pause Init Mark (process weakrefs)";
2814   } else if (unload_cls) {
2815     return "Pause Init Mark (unload classes)";
2816   } else {
2817     return "Pause Init Mark";
2818   }
2819 }
2820 
2821 const char* ShenandoahHeap::final_mark_event_message() const {
2822   bool update_refs = has_forwarded_objects();
2823   bool proc_refs = process_references();
2824   bool unload_cls = unload_classes();
2825 
2826   if (update_refs && proc_refs && unload_cls) {
2827     return "Pause Final Mark (update refs) (process weakrefs) (unload classes)";
2828   } else if (update_refs && proc_refs) {
2829     return "Pause Final Mark (update refs) (process weakrefs)";
2830   } else if (update_refs && unload_cls) {
2831     return "Pause Final Mark (update refs) (unload classes)";
2832   } else if (proc_refs && unload_cls) {
2833     return "Pause Final Mark (process weakrefs) (unload classes)";
2834   } else if (update_refs) {
2835     return "Pause Final Mark (update refs)";
2836   } else if (proc_refs) {
2837     return "Pause Final Mark (process weakrefs)";
2838   } else if (unload_cls) {
2839     return "Pause Final Mark (unload classes)";
2840   } else {
2841     return "Pause Final Mark";
2842   }
2843 }
2844 
2845 const char* ShenandoahHeap::conc_mark_event_message() const {
2846   bool update_refs = has_forwarded_objects();
2847   bool proc_refs = process_references();
2848   bool unload_cls = unload_classes();
2849 
2850   if (update_refs && proc_refs && unload_cls) {
2851     return "Concurrent marking (update refs) (process weakrefs) (unload classes)";
2852   } else if (update_refs && proc_refs) {
2853     return "Concurrent marking (update refs) (process weakrefs)";
2854   } else if (update_refs && unload_cls) {
2855     return "Concurrent marking (update refs) (unload classes)";
2856   } else if (proc_refs && unload_cls) {
2857     return "Concurrent marking (process weakrefs) (unload classes)";
2858   } else if (update_refs) {
2859     return "Concurrent marking (update refs)";
2860   } else if (proc_refs) {
2861     return "Concurrent marking (process weakrefs)";
2862   } else if (unload_cls) {
2863     return "Concurrent marking (unload classes)";
2864   } else {
2865     return "Concurrent marking";
2866   }
2867 }
2868 
2869 const char* ShenandoahHeap::degen_event_message(ShenandoahDegenPoint point) const {
2870   switch (point) {
2871     case _degenerated_unset:
2872       return "Pause Degenerated GC (<UNSET>)";
2873     case _degenerated_traversal:
2874       return "Pause Degenerated GC (Traversal)";
2875     case _degenerated_outside_cycle:
2876       return "Pause Degenerated GC (Outside of Cycle)";
2877     case _degenerated_mark:
2878       return "Pause Degenerated GC (Mark)";
2879     case _degenerated_evac:
2880       return "Pause Degenerated GC (Evacuation)";
2881     case _degenerated_updaterefs:
2882       return "Pause Degenerated GC (Update Refs)";
2883     default:
2884       ShouldNotReachHere();
2885       return "ERROR";
2886   }
2887 }
2888 
2889 jushort* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2890 #ifdef ASSERT
2891   assert(_liveness_cache != NULL, "sanity");
2892   assert(worker_id < _max_workers, "sanity");
2893   for (uint i = 0; i < num_regions(); i++) {
2894     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2895   }
2896 #endif
2897   return _liveness_cache[worker_id];
2898 }
2899 
2900 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2901   assert(worker_id < _max_workers, "sanity");
2902   assert(_liveness_cache != NULL, "sanity");
2903   jushort* ld = _liveness_cache[worker_id];
2904   for (uint i = 0; i < num_regions(); i++) {
2905     ShenandoahHeapRegion* r = get_region(i);
2906     jushort live = ld[i];
2907     if (live > 0) {
2908       r->increase_live_data_gc_words(live);
2909       ld[i] = 0;
2910     }
2911   }
2912 }