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                                !ShenandoahConcurrentRoots::should_do_concurrent_class_unloading());
1072     ShenandoahEvacuateUpdateRootsTask roots_task(&rp);
1073     workers()->run_task(&roots_task);
1074   }
1075 
1076 #if COMPILER2_OR_JVMCI
1077   DerivedPointerTable::update_pointers();
1078 #endif
1079 }
1080 
1081 // Returns size in bytes
1082 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1083   if (ShenandoahElasticTLAB) {
1084     // With Elastic TLABs, return the max allowed size, and let the allocation path
1085     // figure out the safe size for current allocation.
1086     return ShenandoahHeapRegion::max_tlab_size_bytes();
1087   } else {
1088     return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());
1089   }
1090 }
1091 
1092 size_t ShenandoahHeap::max_tlab_size() const {
1093   // Returns size in words
1094   return ShenandoahHeapRegion::max_tlab_size_words();
1095 }
1096 
1097 class ShenandoahRetireAndResetGCLABClosure : public ThreadClosure {
1098 public:
1099   void do_thread(Thread* thread) {
1100     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1101     gclab->retire();
1102     if (ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1103       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1104     }
1105   }
1106 };
1107 
1108 void ShenandoahHeap::retire_and_reset_gclabs() {
1109   ShenandoahRetireAndResetGCLABClosure cl;
1110   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1111     cl.do_thread(t);
1112   }
1113   workers()->threads_do(&cl);
1114 }
1115 
1116 void ShenandoahHeap::collect(GCCause::Cause cause) {
1117   control_thread()->request_gc(cause);
1118 }
1119 
1120 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1121   //assert(false, "Shouldn't need to do full collections");
1122 }
1123 
1124 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1125   Space* sp = heap_region_containing(addr);
1126   if (sp != NULL) {
1127     return sp->block_start(addr);
1128   }
1129   return NULL;
1130 }
1131 
1132 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1133   Space* sp = heap_region_containing(addr);
1134   return sp->block_is_obj(addr);
1135 }
1136 
1137 jlong ShenandoahHeap::millis_since_last_gc() {
1138   double v = heuristics()->time_since_last_gc() * 1000;
1139   assert(0 <= v && v <= max_jlong, "value should fit: %f", v);
1140   return (jlong)v;
1141 }
1142 
1143 void ShenandoahHeap::prepare_for_verify() {
1144   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
1145     make_parsable(false);
1146   }
1147 }
1148 
1149 void ShenandoahHeap::print_gc_threads_on(outputStream* st) const {
1150   workers()->print_worker_threads_on(st);
1151   if (ShenandoahStringDedup::is_enabled()) {
1152     ShenandoahStringDedup::print_worker_threads_on(st);
1153   }
1154 }
1155 
1156 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1157   workers()->threads_do(tcl);
1158   if (_safepoint_workers != NULL) {
1159     _safepoint_workers->threads_do(tcl);
1160   }
1161   if (ShenandoahStringDedup::is_enabled()) {
1162     ShenandoahStringDedup::threads_do(tcl);
1163   }
1164 }
1165 
1166 void ShenandoahHeap::print_tracing_info() const {
1167   LogTarget(Info, gc, stats) lt;
1168   if (lt.is_enabled()) {
1169     ResourceMark rm;
1170     LogStream ls(lt);
1171 
1172     phase_timings()->print_on(&ls);
1173 
1174     ls.cr();
1175     ls.cr();
1176 
1177     shenandoah_policy()->print_gc_stats(&ls);
1178 
1179     ls.cr();
1180     ls.cr();
1181 
1182     if (ShenandoahPacing) {
1183       pacer()->print_on(&ls);
1184     }
1185 
1186     ls.cr();
1187     ls.cr();
1188 
1189     if (ShenandoahAllocationTrace) {
1190       assert(alloc_tracker() != NULL, "Must be");
1191       alloc_tracker()->print_on(&ls);
1192     } else {
1193       ls.print_cr("  Allocation tracing is disabled, use -XX:+ShenandoahAllocationTrace to enable.");
1194     }
1195   }
1196 }
1197 
1198 void ShenandoahHeap::verify(VerifyOption vo) {
1199   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1200     if (ShenandoahVerify) {
1201       verifier()->verify_generic(vo);
1202     } else {
1203       // TODO: Consider allocating verification bitmaps on demand,
1204       // and turn this on unconditionally.
1205     }
1206   }
1207 }
1208 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1209   return _free_set->capacity();
1210 }
1211 
1212 class ObjectIterateScanRootClosure : public BasicOopIterateClosure {
1213 private:
1214   MarkBitMap* _bitmap;
1215   Stack<oop,mtGC>* _oop_stack;
1216 
1217   template <class T>
1218   void do_oop_work(T* p) {
1219     T o = RawAccess<>::oop_load(p);
1220     if (!CompressedOops::is_null(o)) {
1221       oop obj = CompressedOops::decode_not_null(o);
1222       obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
1223       assert(oopDesc::is_oop(obj), "must be a valid oop");
1224       if (!_bitmap->is_marked((HeapWord*) obj)) {
1225         _bitmap->mark((HeapWord*) obj);
1226         _oop_stack->push(obj);
1227       }
1228     }
1229   }
1230 public:
1231   ObjectIterateScanRootClosure(MarkBitMap* bitmap, Stack<oop,mtGC>* oop_stack) :
1232     _bitmap(bitmap), _oop_stack(oop_stack) {}
1233   void do_oop(oop* p)       { do_oop_work(p); }
1234   void do_oop(narrowOop* p) { do_oop_work(p); }
1235 };
1236 
1237 /*
1238  * This is public API, used in preparation of object_iterate().
1239  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1240  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1241  * control, we call SH::make_tlabs_parsable().
1242  */
1243 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1244   // No-op.
1245 }
1246 
1247 /*
1248  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1249  *
1250  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1251  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1252  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1253  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1254  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1255  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1256  * wiped the bitmap in preparation for next marking).
1257  *
1258  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1259  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1260  * is allowed to report dead objects, but is not required to do so.
1261  */
1262 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1263   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1264   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1265     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1266     return;
1267   }
1268 
1269   // Reset bitmap
1270   _aux_bit_map.clear();
1271 
1272   Stack<oop,mtGC> oop_stack;
1273 
1274   // First, we process GC roots according to current GC cycle. This populates the work stack with initial objects.
1275   ShenandoahHeapIterationRootScanner rp;
1276   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1277 
1278   if (unload_classes()) {
1279     rp.strong_roots_do(&oops);
1280   } else {
1281     rp.roots_do(&oops);
1282   }
1283 
1284   // Work through the oop stack to traverse heap.
1285   while (! oop_stack.is_empty()) {
1286     oop obj = oop_stack.pop();
1287     assert(oopDesc::is_oop(obj), "must be a valid oop");
1288     cl->do_object(obj);
1289     obj->oop_iterate(&oops);
1290   }
1291 
1292   assert(oop_stack.is_empty(), "should be empty");
1293 
1294   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1295     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1296   }
1297 }
1298 
1299 void ShenandoahHeap::safe_object_iterate(ObjectClosure* cl) {
1300   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1301   object_iterate(cl);
1302 }
1303 
1304 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1305   for (size_t i = 0; i < num_regions(); i++) {
1306     ShenandoahHeapRegion* current = get_region(i);
1307     blk->heap_region_do(current);
1308   }
1309 }
1310 
1311 class ShenandoahParallelHeapRegionTask : public AbstractGangTask {
1312 private:
1313   ShenandoahHeap* const _heap;
1314   ShenandoahHeapRegionClosure* const _blk;
1315 
1316   DEFINE_PAD_MINUS_SIZE(0, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile size_t));
1317   volatile size_t _index;
1318   DEFINE_PAD_MINUS_SIZE(1, DEFAULT_CACHE_LINE_SIZE, 0);
1319 
1320 public:
1321   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1322           AbstractGangTask("Parallel Region Task"),
1323           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1324 
1325   void work(uint worker_id) {
1326     size_t stride = ShenandoahParallelRegionStride;
1327 
1328     size_t max = _heap->num_regions();
1329     while (_index < max) {
1330       size_t cur = Atomic::add(stride, &_index) - stride;
1331       size_t start = cur;
1332       size_t end = MIN2(cur + stride, max);
1333       if (start >= max) break;
1334 
1335       for (size_t i = cur; i < end; i++) {
1336         ShenandoahHeapRegion* current = _heap->get_region(i);
1337         _blk->heap_region_do(current);
1338       }
1339     }
1340   }
1341 };
1342 
1343 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1344   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1345   if (num_regions() > ShenandoahParallelRegionStride) {
1346     ShenandoahParallelHeapRegionTask task(blk);
1347     workers()->run_task(&task);
1348   } else {
1349     heap_region_iterate(blk);
1350   }
1351 }
1352 
1353 class ShenandoahClearLivenessClosure : public ShenandoahHeapRegionClosure {
1354 private:
1355   ShenandoahMarkingContext* const _ctx;
1356 public:
1357   ShenandoahClearLivenessClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1358 
1359   void heap_region_do(ShenandoahHeapRegion* r) {
1360     if (r->is_active()) {
1361       r->clear_live_data();
1362       _ctx->capture_top_at_mark_start(r);
1363     } else {
1364       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number());
1365       assert(_ctx->top_at_mark_start(r) == r->top(),
1366              "Region " SIZE_FORMAT " should already have correct TAMS", r->region_number());
1367     }
1368   }
1369 
1370   bool is_thread_safe() { return true; }
1371 };
1372 
1373 void ShenandoahHeap::op_init_mark() {
1374   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1375   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
1376 
1377   assert(marking_context()->is_bitmap_clear(), "need clear marking bitmap");
1378   assert(!marking_context()->is_complete(), "should not be complete");
1379 
1380   if (ShenandoahVerify) {
1381     verifier()->verify_before_concmark();
1382   }
1383 
1384   if (VerifyBeforeGC) {
1385     Universe::verify();
1386   }
1387 
1388   set_concurrent_mark_in_progress(true);
1389   // We need to reset all TLABs because we'd lose marks on all objects allocated in them.
1390   {
1391     ShenandoahGCPhase phase(ShenandoahPhaseTimings::make_parsable);
1392     make_parsable(true);
1393   }
1394 
1395   {
1396     ShenandoahGCPhase phase(ShenandoahPhaseTimings::clear_liveness);
1397     ShenandoahClearLivenessClosure clc;
1398     parallel_heap_region_iterate(&clc);
1399   }
1400 
1401   // Make above changes visible to worker threads
1402   OrderAccess::fence();
1403 
1404   concurrent_mark()->mark_roots(ShenandoahPhaseTimings::scan_roots);
1405 
1406   if (UseTLAB) {
1407     ShenandoahGCPhase phase(ShenandoahPhaseTimings::resize_tlabs);
1408     resize_tlabs();
1409   }
1410 
1411   if (ShenandoahPacing) {
1412     pacer()->setup_for_mark();
1413   }
1414 }
1415 
1416 void ShenandoahHeap::op_mark() {
1417   concurrent_mark()->mark_from_roots();
1418 }
1419 
1420 class ShenandoahCompleteLivenessClosure : public ShenandoahHeapRegionClosure {
1421 private:
1422   ShenandoahMarkingContext* const _ctx;
1423 public:
1424   ShenandoahCompleteLivenessClosure() : _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
1425 
1426   void heap_region_do(ShenandoahHeapRegion* r) {
1427     if (r->is_active()) {
1428       HeapWord *tams = _ctx->top_at_mark_start(r);
1429       HeapWord *top = r->top();
1430       if (top > tams) {
1431         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1432       }
1433     } else {
1434       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number());
1435       assert(_ctx->top_at_mark_start(r) == r->top(),
1436              "Region " SIZE_FORMAT " should have correct TAMS", r->region_number());
1437     }
1438   }
1439 
1440   bool is_thread_safe() { return true; }
1441 };
1442 
1443 void ShenandoahHeap::op_final_mark() {
1444   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1445 
1446   // It is critical that we
1447   // evacuate roots right after finishing marking, so that we don't
1448   // get unmarked objects in the roots.
1449 
1450   if (!cancelled_gc()) {
1451     concurrent_mark()->finish_mark_from_roots(/* full_gc = */ false);
1452 
1453     if (has_forwarded_objects()) {
1454       // Degen may be caused by failed evacuation of roots
1455       if (is_degenerated_gc_in_progress()) {
1456         concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots);
1457       } else {
1458         concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::update_roots);
1459       }
1460    }
1461 
1462     if (ShenandoahVerify) {
1463       verifier()->verify_roots_no_forwarded();
1464     }
1465 
1466     stop_concurrent_marking();
1467 
1468     {
1469       ShenandoahGCPhase phase(ShenandoahPhaseTimings::complete_liveness);
1470 
1471       // All allocations past TAMS are implicitly live, adjust the region data.
1472       // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1473       ShenandoahCompleteLivenessClosure cl;
1474       parallel_heap_region_iterate(&cl);
1475     }
1476 
1477     {
1478       ShenandoahGCPhase prepare_evac(ShenandoahPhaseTimings::prepare_evac);
1479 
1480       make_parsable(true);
1481 
1482       trash_cset_regions();
1483 
1484       {
1485         ShenandoahHeapLocker locker(lock());
1486         _collection_set->clear();
1487         _free_set->clear();
1488 
1489         heuristics()->choose_collection_set(_collection_set);
1490 
1491         _free_set->rebuild();
1492       }
1493     }
1494 
1495     // If collection set has candidates, start evacuation.
1496     // Otherwise, bypass the rest of the cycle.
1497     if (!collection_set()->is_empty()) {
1498       ShenandoahGCPhase init_evac(ShenandoahPhaseTimings::init_evac);
1499 
1500       if (ShenandoahVerify) {
1501         verifier()->verify_before_evacuation();
1502       }
1503 
1504       set_evacuation_in_progress(true);
1505       // From here on, we need to update references.
1506       set_has_forwarded_objects(true);
1507 
1508       if (!is_degenerated_gc_in_progress()) {
1509         prepare_concurrent_unloading();
1510         evacuate_and_update_roots();
1511       }
1512 
1513       if (ShenandoahPacing) {
1514         pacer()->setup_for_evac();
1515       }
1516 
1517       if (ShenandoahVerify) {
1518         ShenandoahRootVerifier::RootTypes types = ShenandoahRootVerifier::None;
1519         if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) {
1520           types = ShenandoahRootVerifier::combine(ShenandoahRootVerifier::JNIHandleRoots, ShenandoahRootVerifier::WeakRoots);
1521           types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::CLDGRoots);
1522         }
1523 
1524         if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
1525           types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::CodeRoots);
1526         }
1527         verifier()->verify_roots_no_forwarded_except(types);
1528         verifier()->verify_during_evacuation();
1529       }
1530     } else {
1531       if (ShenandoahVerify) {
1532         verifier()->verify_after_concmark();
1533       }
1534 
1535       if (VerifyAfterGC) {
1536         Universe::verify();
1537       }
1538     }
1539 
1540   } else {
1541     concurrent_mark()->cancel();
1542     stop_concurrent_marking();
1543 
1544     if (process_references()) {
1545       // Abandon reference processing right away: pre-cleaning must have failed.
1546       ReferenceProcessor *rp = ref_processor();
1547       rp->disable_discovery();
1548       rp->abandon_partial_discovery();
1549       rp->verify_no_references_recorded();
1550     }
1551   }
1552 }
1553 
1554 void ShenandoahHeap::op_final_evac() {
1555   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1556 
1557   set_evacuation_in_progress(false);
1558 
1559   retire_and_reset_gclabs();
1560 
1561   if (ShenandoahVerify) {
1562     verifier()->verify_after_evacuation();
1563   }
1564 
1565   if (VerifyAfterGC) {
1566     Universe::verify();
1567   }
1568 }
1569 
1570 void ShenandoahHeap::op_conc_evac() {
1571   ShenandoahEvacuationTask task(this, _collection_set, true);
1572   workers()->run_task(&task);
1573 }
1574 
1575 void ShenandoahHeap::op_stw_evac() {
1576   ShenandoahEvacuationTask task(this, _collection_set, false);
1577   workers()->run_task(&task);
1578 }
1579 
1580 void ShenandoahHeap::op_updaterefs() {
1581   update_heap_references(true);
1582 }
1583 
1584 void ShenandoahHeap::op_cleanup() {
1585   free_set()->recycle_trash();
1586 }
1587 
1588 class ShenandoahConcurrentRootsEvacUpdateTask : public AbstractGangTask {
1589 private:
1590   ShenandoahVMRoots<true /*concurrent*/>        _vm_roots;
1591   ShenandoahWeakRoots<true /*concurrent*/>      _weak_roots;
1592   ShenandoahClassLoaderDataRoots<true /*concurrent*/, false /*single threaded*/> _cld_roots;
1593 
1594 public:
1595   ShenandoahConcurrentRootsEvacUpdateTask() :
1596     AbstractGangTask("Shenandoah Evacuate/Update Concurrent Roots Task") {
1597   }
1598 
1599   void work(uint worker_id) {
1600     ShenandoahEvacOOMScope oom;
1601     {
1602       // jni_roots and weak_roots are OopStorage backed roots, concurrent iteration
1603       // may race against OopStorage::release() calls.
1604       ShenandoahEvacUpdateOopStorageRootsClosure cl;
1605       _vm_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl);
1606       _weak_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl);
1607     }
1608 
1609     {
1610       ShenandoahEvacuateUpdateRootsClosure cl;
1611       CLDToOopClosure clds(&cl, ClassLoaderData::_claim_strong);
1612       _cld_roots.cld_do(&clds);
1613     }
1614   }
1615 };
1616 
1617 void ShenandoahHeap::op_roots() {
1618   if (is_evacuation_in_progress()) {
1619     if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
1620       _unloader.unload();
1621     }
1622 
1623     if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) {
1624       ShenandoahConcurrentRootsEvacUpdateTask task;
1625       workers()->run_task(&task);
1626     }
1627   }
1628 }
1629 
1630 void ShenandoahHeap::op_reset() {
1631   reset_mark_bitmap();
1632 }
1633 
1634 void ShenandoahHeap::op_preclean() {
1635   concurrent_mark()->preclean_weak_refs();
1636 }
1637 
1638 void ShenandoahHeap::op_init_traversal() {
1639   traversal_gc()->init_traversal_collection();
1640 }
1641 
1642 void ShenandoahHeap::op_traversal() {
1643   traversal_gc()->concurrent_traversal_collection();
1644 }
1645 
1646 void ShenandoahHeap::op_final_traversal() {
1647   traversal_gc()->final_traversal_collection();
1648 }
1649 
1650 void ShenandoahHeap::op_full(GCCause::Cause cause) {
1651   ShenandoahMetricsSnapshot metrics;
1652   metrics.snap_before();
1653 
1654   full_gc()->do_it(cause);
1655   if (UseTLAB) {
1656     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_resize_tlabs);
1657     resize_all_tlabs();
1658   }
1659 
1660   metrics.snap_after();
1661 
1662   if (metrics.is_good_progress()) {
1663     _progress_last_gc.set();
1664   } else {
1665     // Nothing to do. Tell the allocation path that we have failed to make
1666     // progress, and it can finally fail.
1667     _progress_last_gc.unset();
1668   }
1669 }
1670 
1671 void ShenandoahHeap::op_degenerated(ShenandoahDegenPoint point) {
1672   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
1673   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
1674   // some phase, we have to upgrade the Degenerate GC to Full GC.
1675 
1676   clear_cancelled_gc();
1677 
1678   ShenandoahMetricsSnapshot metrics;
1679   metrics.snap_before();
1680 
1681   switch (point) {
1682     case _degenerated_traversal:
1683       {
1684         // Drop the collection set. Note: this leaves some already forwarded objects
1685         // behind, which may be problematic, see comments for ShenandoahEvacAssist
1686         // workarounds in ShenandoahTraversalHeuristics.
1687 
1688         ShenandoahHeapLocker locker(lock());
1689         collection_set()->clear_current_index();
1690         for (size_t i = 0; i < collection_set()->count(); i++) {
1691           ShenandoahHeapRegion* r = collection_set()->next();
1692           r->make_regular_bypass();
1693         }
1694         collection_set()->clear();
1695       }
1696       op_final_traversal();
1697       op_cleanup();
1698       return;
1699 
1700     // The cases below form the Duff's-like device: it describes the actual GC cycle,
1701     // but enters it at different points, depending on which concurrent phase had
1702     // degenerated.
1703 
1704     case _degenerated_outside_cycle:
1705       // We have degenerated from outside the cycle, which means something is bad with
1706       // the heap, most probably heavy humongous fragmentation, or we are very low on free
1707       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
1708       // we can do the most aggressive degen cycle, which includes processing references and
1709       // class unloading, unless those features are explicitly disabled.
1710       //
1711       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
1712       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
1713       set_process_references(heuristics()->can_process_references());
1714       set_unload_classes(heuristics()->can_unload_classes());
1715 
1716       if (is_traversal_mode()) {
1717         // Not possible to degenerate from here, upgrade to Full GC right away.
1718         cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1719         op_degenerated_fail();
1720         return;
1721       }
1722 
1723       op_reset();
1724 
1725       op_init_mark();
1726       if (cancelled_gc()) {
1727         op_degenerated_fail();
1728         return;
1729       }
1730 
1731     case _degenerated_mark:
1732       op_final_mark();
1733       if (cancelled_gc()) {
1734         op_degenerated_fail();
1735         return;
1736       }
1737 
1738       op_cleanup();
1739 
1740     case _degenerated_evac:
1741       // If heuristics thinks we should do the cycle, this flag would be set,
1742       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
1743       if (is_evacuation_in_progress()) {
1744 
1745         // Degeneration under oom-evac protocol might have left some objects in
1746         // collection set un-evacuated. Restart evacuation from the beginning to
1747         // capture all objects. For all the objects that are already evacuated,
1748         // it would be a simple check, which is supposed to be fast. This is also
1749         // safe to do even without degeneration, as CSet iterator is at beginning
1750         // in preparation for evacuation anyway.
1751         //
1752         // Before doing that, we need to make sure we never had any cset-pinned
1753         // regions. This may happen if allocation failure happened when evacuating
1754         // the about-to-be-pinned object, oom-evac protocol left the object in
1755         // the collection set, and then the pin reached the cset region. If we continue
1756         // the cycle here, we would trash the cset and alive objects in it. To avoid
1757         // it, we fail degeneration right away and slide into Full GC to recover.
1758 
1759         {
1760           collection_set()->clear_current_index();
1761 
1762           ShenandoahHeapRegion* r;
1763           while ((r = collection_set()->next()) != NULL) {
1764             if (r->is_pinned()) {
1765               cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1766               op_degenerated_fail();
1767               return;
1768             }
1769           }
1770 
1771           collection_set()->clear_current_index();
1772         }
1773 
1774         op_stw_evac();
1775         if (cancelled_gc()) {
1776           op_degenerated_fail();
1777           return;
1778         }
1779       }
1780 
1781       // If heuristics thinks we should do the cycle, this flag would be set,
1782       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
1783       if (has_forwarded_objects()) {
1784         op_init_updaterefs();
1785         if (cancelled_gc()) {
1786           op_degenerated_fail();
1787           return;
1788         }
1789       }
1790 
1791     case _degenerated_updaterefs:
1792       if (has_forwarded_objects()) {
1793         op_final_updaterefs();
1794         if (cancelled_gc()) {
1795           op_degenerated_fail();
1796           return;
1797         }
1798       }
1799 
1800       op_cleanup();
1801       break;
1802 
1803     default:
1804       ShouldNotReachHere();
1805   }
1806 
1807   if (ShenandoahVerify) {
1808     verifier()->verify_after_degenerated();
1809   }
1810 
1811   if (VerifyAfterGC) {
1812     Universe::verify();
1813   }
1814 
1815   metrics.snap_after();
1816 
1817   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
1818   // because that probably means the heap is overloaded and/or fragmented.
1819   if (!metrics.is_good_progress()) {
1820     _progress_last_gc.unset();
1821     cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1822     op_degenerated_futile();
1823   } else {
1824     _progress_last_gc.set();
1825   }
1826 }
1827 
1828 void ShenandoahHeap::op_degenerated_fail() {
1829   log_info(gc)("Cannot finish degeneration, upgrading to Full GC");
1830   shenandoah_policy()->record_degenerated_upgrade_to_full();
1831   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1832 }
1833 
1834 void ShenandoahHeap::op_degenerated_futile() {
1835   shenandoah_policy()->record_degenerated_upgrade_to_full();
1836   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1837 }
1838 
1839 void ShenandoahHeap::stop_concurrent_marking() {
1840   assert(is_concurrent_mark_in_progress(), "How else could we get here?");
1841   set_concurrent_mark_in_progress(false);
1842   if (!cancelled_gc()) {
1843     // If we needed to update refs, and concurrent marking has been cancelled,
1844     // we need to finish updating references.
1845     set_has_forwarded_objects(false);
1846     mark_complete_marking_context();
1847   }
1848 }
1849 
1850 void ShenandoahHeap::force_satb_flush_all_threads() {
1851   if (!is_concurrent_mark_in_progress() && !is_concurrent_traversal_in_progress()) {
1852     // No need to flush SATBs
1853     return;
1854   }
1855 
1856   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1857     ShenandoahThreadLocalData::set_force_satb_flush(t, true);
1858   }
1859   // The threads are not "acquiring" their thread-local data, but it does not
1860   // hurt to "release" the updates here anyway.
1861   OrderAccess::fence();
1862 }
1863 
1864 void ShenandoahHeap::set_gc_state_all_threads(char state) {
1865   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1866     ShenandoahThreadLocalData::set_gc_state(t, state);
1867   }
1868 }
1869 
1870 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1871   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1872   _gc_state.set_cond(mask, value);
1873   set_gc_state_all_threads(_gc_state.raw_value());
1874 }
1875 
1876 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1877   if (has_forwarded_objects()) {
1878     set_gc_state_mask(MARKING | UPDATEREFS, in_progress);
1879   } else {
1880     set_gc_state_mask(MARKING, in_progress);
1881   }
1882   ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1883 }
1884 
1885 void ShenandoahHeap::set_concurrent_traversal_in_progress(bool in_progress) {
1886    set_gc_state_mask(TRAVERSAL | HAS_FORWARDED | UPDATEREFS, in_progress);
1887    ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1888 }
1889 
1890 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1891   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1892   set_gc_state_mask(EVACUATION, in_progress);
1893 }
1894 
1895 void ShenandoahHeap::ref_processing_init() {
1896   assert(_max_workers > 0, "Sanity");
1897 
1898   _ref_processor =
1899     new ReferenceProcessor(&_subject_to_discovery,  // is_subject_to_discovery
1900                            ParallelRefProcEnabled,  // MT processing
1901                            _max_workers,            // Degree of MT processing
1902                            true,                    // MT discovery
1903                            _max_workers,            // Degree of MT discovery
1904                            false,                   // Reference discovery is not atomic
1905                            NULL,                    // No closure, should be installed before use
1906                            true);                   // Scale worker threads
1907 
1908   shenandoah_assert_rp_isalive_not_installed();
1909 }
1910 
1911 GCTracer* ShenandoahHeap::tracer() {
1912   return shenandoah_policy()->tracer();
1913 }
1914 
1915 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1916   return _free_set->used();
1917 }
1918 
1919 bool ShenandoahHeap::try_cancel_gc() {
1920   while (true) {
1921     jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
1922     if (prev == CANCELLABLE) return true;
1923     else if (prev == CANCELLED) return false;
1924     assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers");
1925     assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED");
1926     {
1927       // We need to provide a safepoint here, otherwise we might
1928       // spin forever if a SP is pending.
1929       ThreadBlockInVM sp(JavaThread::current());
1930       SpinPause();
1931     }
1932   }
1933 }
1934 
1935 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1936   if (try_cancel_gc()) {
1937     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1938     log_info(gc)("%s", msg.buffer());
1939     Events::log(Thread::current(), "%s", msg.buffer());
1940   }
1941 }
1942 
1943 uint ShenandoahHeap::max_workers() {
1944   return _max_workers;
1945 }
1946 
1947 void ShenandoahHeap::stop() {
1948   // The shutdown sequence should be able to terminate when GC is running.
1949 
1950   // Step 0. Notify policy to disable event recording.
1951   _shenandoah_policy->record_shutdown();
1952 
1953   // Step 1. Notify control thread that we are in shutdown.
1954   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1955   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1956   control_thread()->prepare_for_graceful_shutdown();
1957 
1958   // Step 2. Notify GC workers that we are cancelling GC.
1959   cancel_gc(GCCause::_shenandoah_stop_vm);
1960 
1961   // Step 3. Wait until GC worker exits normally.
1962   control_thread()->stop();
1963 
1964   // Step 4. Stop String Dedup thread if it is active
1965   if (ShenandoahStringDedup::is_enabled()) {
1966     ShenandoahStringDedup::stop();
1967   }
1968 }
1969 
1970 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
1971   if (!unload_classes()) return;
1972   bool purged_class;
1973 
1974   // Unload classes and purge SystemDictionary.
1975   {
1976     ShenandoahGCPhase phase(full_gc ?
1977                             ShenandoahPhaseTimings::full_gc_purge_class_unload :
1978                             ShenandoahPhaseTimings::purge_class_unload);
1979     purged_class = SystemDictionary::do_unloading(gc_timer());
1980   }
1981 
1982   {
1983     ShenandoahGCPhase phase(full_gc ?
1984                             ShenandoahPhaseTimings::full_gc_purge_par :
1985                             ShenandoahPhaseTimings::purge_par);
1986     ShenandoahIsAliveSelector is_alive;
1987     uint num_workers = _workers->active_workers();
1988     ShenandoahClassUnloadingTask unlink_task(is_alive.is_alive_closure(), num_workers, purged_class);
1989     _workers->run_task(&unlink_task);
1990   }
1991 
1992   {
1993     ShenandoahGCPhase phase(full_gc ?
1994                             ShenandoahPhaseTimings::full_gc_purge_cldg :
1995                             ShenandoahPhaseTimings::purge_cldg);
1996     ClassLoaderDataGraph::purge();
1997   }
1998   // Resize and verify metaspace
1999   MetaspaceGC::compute_new_size();
2000   MetaspaceUtils::verify_metrics();
2001 }
2002 
2003 // Weak roots are either pre-evacuated (final mark) or updated (final updaterefs),
2004 // so they should not have forwarded oops.
2005 // However, we do need to "null" dead oops in the roots, if can not be done
2006 // in concurrent cycles.
2007 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
2008   ShenandoahGCPhase root_phase(full_gc ?
2009                                ShenandoahPhaseTimings::full_gc_purge :
2010                                ShenandoahPhaseTimings::purge);
2011   uint num_workers = _workers->active_workers();
2012   ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
2013                                                ShenandoahPhaseTimings::full_gc_purge_par :
2014                                                ShenandoahPhaseTimings::purge_par;
2015   // Cleanup weak roots
2016   ShenandoahGCPhase phase(timing_phase);
2017   ShenandoahIsAliveClosure is_alive;
2018 #ifdef ASSERT
2019   ShenandoahAssertNotForwardedClosure verify_cl;
2020   ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
2021     cleaning_task(&is_alive, &verify_cl, num_workers);
2022 #else
2023   ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
2024     cleaning_task(&is_alive, &do_nothing_cl, num_workers);
2025 #endif
2026   _workers->run_task(&cleaning_task);
2027 }
2028 
2029 void ShenandoahHeap::parallel_cleaning(bool full_gc) {
2030   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2031   stw_process_weak_roots(full_gc);
2032   if (!ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
2033     stw_unload_classes(full_gc);
2034   }
2035 }
2036 
2037 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
2038   set_gc_state_mask(HAS_FORWARDED, cond);
2039 }
2040 
2041 void ShenandoahHeap::set_process_references(bool pr) {
2042   _process_references.set_cond(pr);
2043 }
2044 
2045 void ShenandoahHeap::set_unload_classes(bool uc) {
2046   _unload_classes.set_cond(uc);
2047 }
2048 
2049 bool ShenandoahHeap::process_references() const {
2050   return _process_references.is_set();
2051 }
2052 
2053 bool ShenandoahHeap::unload_classes() const {
2054   return _unload_classes.is_set();
2055 }
2056 
2057 address ShenandoahHeap::in_cset_fast_test_addr() {
2058   ShenandoahHeap* heap = ShenandoahHeap::heap();
2059   assert(heap->collection_set() != NULL, "Sanity");
2060   return (address) heap->collection_set()->biased_map_address();
2061 }
2062 
2063 address ShenandoahHeap::cancelled_gc_addr() {
2064   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
2065 }
2066 
2067 address ShenandoahHeap::gc_state_addr() {
2068   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
2069 }
2070 
2071 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
2072   return OrderAccess::load_acquire(&_bytes_allocated_since_gc_start);
2073 }
2074 
2075 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
2076   OrderAccess::release_store_fence(&_bytes_allocated_since_gc_start, (size_t)0);
2077 }
2078 
2079 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2080   _degenerated_gc_in_progress.set_cond(in_progress);
2081 }
2082 
2083 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2084   _full_gc_in_progress.set_cond(in_progress);
2085 }
2086 
2087 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2088   assert (is_full_gc_in_progress(), "should be");
2089   _full_gc_move_in_progress.set_cond(in_progress);
2090 }
2091 
2092 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2093   set_gc_state_mask(UPDATEREFS, in_progress);
2094 }
2095 
2096 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2097   ShenandoahCodeRoots::register_nmethod(nm);
2098 }
2099 
2100 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2101   ShenandoahCodeRoots::unregister_nmethod(nm);
2102 }
2103 
2104 void ShenandoahHeap::flush_nmethod(nmethod* nm) {
2105   ShenandoahCodeRoots::flush_nmethod(nm);
2106 }
2107 
2108 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2109   ShenandoahHeapLocker locker(lock());
2110   heap_region_containing(o)->make_pinned();
2111   return o;
2112 }
2113 
2114 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2115   ShenandoahHeapLocker locker(lock());
2116   heap_region_containing(o)->make_unpinned();
2117 }
2118 
2119 GCTimer* ShenandoahHeap::gc_timer() const {
2120   return _gc_timer;
2121 }
2122 
2123 void ShenandoahHeap::prepare_concurrent_unloading() {
2124   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2125   if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
2126     ShenandoahCodeRoots::prepare_concurrent_unloading();
2127     _unloader.prepare();
2128   }
2129 }
2130 
2131 void ShenandoahHeap::finish_concurrent_unloading() {
2132   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2133   if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
2134     _unloader.finish();
2135   }
2136 }
2137 
2138 #ifdef ASSERT
2139 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2140   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2141 
2142   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2143     if (UseDynamicNumberOfGCThreads ||
2144         (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) {
2145       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
2146     } else {
2147       // Use ParallelGCThreads inside safepoints
2148       assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints");
2149     }
2150   } else {
2151     if (UseDynamicNumberOfGCThreads ||
2152         (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) {
2153       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
2154     } else {
2155       // Use ConcGCThreads outside safepoints
2156       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2157     }
2158   }
2159 }
2160 #endif
2161 
2162 ShenandoahVerifier* ShenandoahHeap::verifier() {
2163   guarantee(ShenandoahVerify, "Should be enabled");
2164   assert (_verifier != NULL, "sanity");
2165   return _verifier;
2166 }
2167 
2168 template<class T>
2169 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
2170 private:
2171   T cl;
2172   ShenandoahHeap* _heap;
2173   ShenandoahRegionIterator* _regions;
2174   bool _concurrent;
2175 public:
2176   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions, bool concurrent) :
2177     AbstractGangTask("Concurrent Update References Task"),
2178     cl(T()),
2179     _heap(ShenandoahHeap::heap()),
2180     _regions(regions),
2181     _concurrent(concurrent) {
2182   }
2183 
2184   void work(uint worker_id) {
2185     if (_concurrent) {
2186       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2187       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2188       do_work();
2189     } else {
2190       ShenandoahParallelWorkerSession worker_session(worker_id);
2191       do_work();
2192     }
2193   }
2194 
2195 private:
2196   void do_work() {
2197     ShenandoahHeapRegion* r = _regions->next();
2198     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2199     while (r != NULL) {
2200       HeapWord* top_at_start_ur = r->concurrent_iteration_safe_limit();
2201       assert (top_at_start_ur >= r->bottom(), "sanity");
2202       if (r->is_active() && !r->is_cset()) {
2203         _heap->marked_object_oop_iterate(r, &cl, top_at_start_ur);
2204       }
2205       if (ShenandoahPacing) {
2206         _heap->pacer()->report_updaterefs(pointer_delta(top_at_start_ur, r->bottom()));
2207       }
2208       if (_heap->check_cancelled_gc_and_yield(_concurrent)) {
2209         return;
2210       }
2211       r = _regions->next();
2212     }
2213   }
2214 };
2215 
2216 void ShenandoahHeap::update_heap_references(bool concurrent) {
2217   ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsClosure> task(&_update_refs_iterator, concurrent);
2218   workers()->run_task(&task);
2219 }
2220 
2221 void ShenandoahHeap::op_init_updaterefs() {
2222   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2223 
2224   set_evacuation_in_progress(false);
2225 
2226   retire_and_reset_gclabs();
2227 
2228   if (ShenandoahVerify) {
2229     if (!is_degenerated_gc_in_progress()) {
2230       verifier()->verify_roots_no_forwarded_except(ShenandoahRootVerifier::ThreadRoots);
2231     }
2232     verifier()->verify_before_updaterefs();
2233   }
2234 
2235   set_update_refs_in_progress(true);
2236   make_parsable(true);
2237   for (uint i = 0; i < num_regions(); i++) {
2238     ShenandoahHeapRegion* r = get_region(i);
2239     r->set_concurrent_iteration_safe_limit(r->top());
2240   }
2241 
2242   // Reset iterator.
2243   _update_refs_iterator.reset();
2244 
2245   if (ShenandoahPacing) {
2246     pacer()->setup_for_updaterefs();
2247   }
2248 }
2249 
2250 void ShenandoahHeap::op_final_updaterefs() {
2251   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2252 
2253   finish_concurrent_unloading();
2254 
2255   // Check if there is left-over work, and finish it
2256   if (_update_refs_iterator.has_next()) {
2257     ShenandoahGCPhase final_work(ShenandoahPhaseTimings::final_update_refs_finish_work);
2258 
2259     // Finish updating references where we left off.
2260     clear_cancelled_gc();
2261     update_heap_references(false);
2262   }
2263 
2264   // Clear cancelled GC, if set. On cancellation path, the block before would handle
2265   // everything. On degenerated paths, cancelled gc would not be set anyway.
2266   if (cancelled_gc()) {
2267     clear_cancelled_gc();
2268   }
2269   assert(!cancelled_gc(), "Should have been done right before");
2270 
2271   if (ShenandoahVerify && !is_degenerated_gc_in_progress()) {
2272     verifier()->verify_roots_in_to_space_except(ShenandoahRootVerifier::ThreadRoots);
2273   }
2274 
2275   if (is_degenerated_gc_in_progress()) {
2276     concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots);
2277   } else {
2278     concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::final_update_refs_roots);
2279   }
2280 
2281   // Has to be done before cset is clear
2282   if (ShenandoahVerify) {
2283     verifier()->verify_roots_in_to_space();
2284   }
2285 
2286   ShenandoahGCPhase final_update_refs(ShenandoahPhaseTimings::final_update_refs_recycle);
2287 
2288   trash_cset_regions();
2289   set_has_forwarded_objects(false);
2290   set_update_refs_in_progress(false);
2291 
2292   if (ShenandoahVerify) {
2293     verifier()->verify_after_updaterefs();
2294   }
2295 
2296   if (VerifyAfterGC) {
2297     Universe::verify();
2298   }
2299 
2300   {
2301     ShenandoahHeapLocker locker(lock());
2302     _free_set->rebuild();
2303   }
2304 }
2305 
2306 #ifdef ASSERT
2307 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() {
2308   _lock.assert_owned_by_current_thread();
2309 }
2310 
2311 void ShenandoahHeap::assert_heaplock_not_owned_by_current_thread() {
2312   _lock.assert_not_owned_by_current_thread();
2313 }
2314 
2315 void ShenandoahHeap::assert_heaplock_or_safepoint() {
2316   _lock.assert_owned_by_current_thread_or_safepoint();
2317 }
2318 #endif
2319 
2320 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2321   print_on(st);
2322   print_heap_regions_on(st);
2323 }
2324 
2325 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2326   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2327 
2328   size_t regions_from = _bitmap_regions_per_slice * slice;
2329   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2330   for (size_t g = regions_from; g < regions_to; g++) {
2331     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2332     if (skip_self && g == r->region_number()) continue;
2333     if (get_region(g)->is_committed()) {
2334       return true;
2335     }
2336   }
2337   return false;
2338 }
2339 
2340 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2341   assert_heaplock_owned_by_current_thread();
2342 
2343   // Bitmaps in special regions do not need commits
2344   if (_bitmap_region_special) {
2345     return true;
2346   }
2347 
2348   if (is_bitmap_slice_committed(r, true)) {
2349     // Some other region from the group is already committed, meaning the bitmap
2350     // slice is already committed, we exit right away.
2351     return true;
2352   }
2353 
2354   // Commit the bitmap slice:
2355   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2356   size_t off = _bitmap_bytes_per_slice * slice;
2357   size_t len = _bitmap_bytes_per_slice;
2358   if (!os::commit_memory((char*)_bitmap_region.start() + off, len, false)) {
2359     return false;
2360   }
2361   return true;
2362 }
2363 
2364 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2365   assert_heaplock_owned_by_current_thread();
2366 
2367   // Bitmaps in special regions do not need uncommits
2368   if (_bitmap_region_special) {
2369     return true;
2370   }
2371 
2372   if (is_bitmap_slice_committed(r, true)) {
2373     // Some other region from the group is still committed, meaning the bitmap
2374     // slice is should stay committed, exit right away.
2375     return true;
2376   }
2377 
2378   // Uncommit the bitmap slice:
2379   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2380   size_t off = _bitmap_bytes_per_slice * slice;
2381   size_t len = _bitmap_bytes_per_slice;
2382   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2383     return false;
2384   }
2385   return true;
2386 }
2387 
2388 void ShenandoahHeap::safepoint_synchronize_begin() {
2389   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2390     SuspendibleThreadSet::synchronize();
2391   }
2392 }
2393 
2394 void ShenandoahHeap::safepoint_synchronize_end() {
2395   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2396     SuspendibleThreadSet::desynchronize();
2397   }
2398 }
2399 
2400 void ShenandoahHeap::vmop_entry_init_mark() {
2401   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2402   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2403   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark_gross);
2404 
2405   try_inject_alloc_failure();
2406   VM_ShenandoahInitMark op;
2407   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
2408 }
2409 
2410 void ShenandoahHeap::vmop_entry_final_mark() {
2411   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2412   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2413   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark_gross);
2414 
2415   try_inject_alloc_failure();
2416   VM_ShenandoahFinalMarkStartEvac op;
2417   VMThread::execute(&op); // jump to entry_final_mark under safepoint
2418 }
2419 
2420 void ShenandoahHeap::vmop_entry_final_evac() {
2421   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2422   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2423   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_gross);
2424 
2425   VM_ShenandoahFinalEvac op;
2426   VMThread::execute(&op); // jump to entry_final_evac under safepoint
2427 }
2428 
2429 void ShenandoahHeap::vmop_entry_init_updaterefs() {
2430   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2431   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2432   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_gross);
2433 
2434   try_inject_alloc_failure();
2435   VM_ShenandoahInitUpdateRefs op;
2436   VMThread::execute(&op);
2437 }
2438 
2439 void ShenandoahHeap::vmop_entry_final_updaterefs() {
2440   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2441   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2442   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_gross);
2443 
2444   try_inject_alloc_failure();
2445   VM_ShenandoahFinalUpdateRefs op;
2446   VMThread::execute(&op);
2447 }
2448 
2449 void ShenandoahHeap::vmop_entry_init_traversal() {
2450   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2451   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2452   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc_gross);
2453 
2454   try_inject_alloc_failure();
2455   VM_ShenandoahInitTraversalGC op;
2456   VMThread::execute(&op);
2457 }
2458 
2459 void ShenandoahHeap::vmop_entry_final_traversal() {
2460   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2461   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2462   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc_gross);
2463 
2464   try_inject_alloc_failure();
2465   VM_ShenandoahFinalTraversalGC op;
2466   VMThread::execute(&op);
2467 }
2468 
2469 void ShenandoahHeap::vmop_entry_full(GCCause::Cause cause) {
2470   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2471   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2472   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_gross);
2473 
2474   try_inject_alloc_failure();
2475   VM_ShenandoahFullGC op(cause);
2476   VMThread::execute(&op);
2477 }
2478 
2479 void ShenandoahHeap::vmop_degenerated(ShenandoahDegenPoint point) {
2480   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2481   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2482   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_gross);
2483 
2484   VM_ShenandoahDegeneratedGC degenerated_gc((int)point);
2485   VMThread::execute(&degenerated_gc);
2486 }
2487 
2488 void ShenandoahHeap::entry_init_mark() {
2489   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2490   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark);
2491   const char* msg = init_mark_event_message();
2492   GCTraceTime(Info, gc) time(msg, gc_timer());
2493   EventMark em("%s", msg);
2494 
2495   ShenandoahWorkerScope scope(workers(),
2496                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
2497                               "init marking");
2498 
2499   op_init_mark();
2500 }
2501 
2502 void ShenandoahHeap::entry_final_mark() {
2503   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2504   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark);
2505   const char* msg = final_mark_event_message();
2506   GCTraceTime(Info, gc) time(msg, gc_timer());
2507   EventMark em("%s", msg);
2508 
2509   ShenandoahWorkerScope scope(workers(),
2510                               ShenandoahWorkerPolicy::calc_workers_for_final_marking(),
2511                               "final marking");
2512 
2513   op_final_mark();
2514 }
2515 
2516 void ShenandoahHeap::entry_final_evac() {
2517   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2518   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac);
2519   static const char* msg = "Pause Final Evac";
2520   GCTraceTime(Info, gc) time(msg, gc_timer());
2521   EventMark em("%s", msg);
2522 
2523   op_final_evac();
2524 }
2525 
2526 void ShenandoahHeap::entry_init_updaterefs() {
2527   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2528   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs);
2529 
2530   static const char* msg = "Pause Init Update Refs";
2531   GCTraceTime(Info, gc) time(msg, gc_timer());
2532   EventMark em("%s", msg);
2533 
2534   // No workers used in this phase, no setup required
2535 
2536   op_init_updaterefs();
2537 }
2538 
2539 void ShenandoahHeap::entry_final_updaterefs() {
2540   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2541   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs);
2542 
2543   static const char* msg = "Pause Final Update Refs";
2544   GCTraceTime(Info, gc) time(msg, gc_timer());
2545   EventMark em("%s", msg);
2546 
2547   ShenandoahWorkerScope scope(workers(),
2548                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
2549                               "final reference update");
2550 
2551   op_final_updaterefs();
2552 }
2553 
2554 void ShenandoahHeap::entry_init_traversal() {
2555   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2556   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc);
2557 
2558   static const char* msg = "Pause Init Traversal";
2559   GCTraceTime(Info, gc) time(msg, gc_timer());
2560   EventMark em("%s", msg);
2561 
2562   ShenandoahWorkerScope scope(workers(),
2563                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2564                               "init traversal");
2565 
2566   op_init_traversal();
2567 }
2568 
2569 void ShenandoahHeap::entry_final_traversal() {
2570   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2571   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc);
2572 
2573   static const char* msg = "Pause Final Traversal";
2574   GCTraceTime(Info, gc) time(msg, gc_timer());
2575   EventMark em("%s", msg);
2576 
2577   ShenandoahWorkerScope scope(workers(),
2578                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2579                               "final traversal");
2580 
2581   op_final_traversal();
2582 }
2583 
2584 void ShenandoahHeap::entry_full(GCCause::Cause cause) {
2585   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2586   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc);
2587 
2588   static const char* msg = "Pause Full";
2589   GCTraceTime(Info, gc) time(msg, gc_timer(), cause, true);
2590   EventMark em("%s", msg);
2591 
2592   ShenandoahWorkerScope scope(workers(),
2593                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
2594                               "full gc");
2595 
2596   op_full(cause);
2597 }
2598 
2599 void ShenandoahHeap::entry_degenerated(int point) {
2600   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2601   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc);
2602 
2603   ShenandoahDegenPoint dpoint = (ShenandoahDegenPoint)point;
2604   const char* msg = degen_event_message(dpoint);
2605   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2606   EventMark em("%s", msg);
2607 
2608   ShenandoahWorkerScope scope(workers(),
2609                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
2610                               "stw degenerated gc");
2611 
2612   set_degenerated_gc_in_progress(true);
2613   op_degenerated(dpoint);
2614   set_degenerated_gc_in_progress(false);
2615 }
2616 
2617 void ShenandoahHeap::entry_mark() {
2618   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2619 
2620   const char* msg = conc_mark_event_message();
2621   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2622   EventMark em("%s", msg);
2623 
2624   ShenandoahWorkerScope scope(workers(),
2625                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
2626                               "concurrent marking");
2627 
2628   try_inject_alloc_failure();
2629   op_mark();
2630 }
2631 
2632 void ShenandoahHeap::entry_evac() {
2633   ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac);
2634   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2635 
2636   static const char* msg = "Concurrent evacuation";
2637   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2638   EventMark em("%s", msg);
2639 
2640   ShenandoahWorkerScope scope(workers(),
2641                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
2642                               "concurrent evacuation");
2643 
2644   try_inject_alloc_failure();
2645   op_conc_evac();
2646 }
2647 
2648 void ShenandoahHeap::entry_updaterefs() {
2649   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs);
2650 
2651   static const char* msg = "Concurrent update references";
2652   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2653   EventMark em("%s", msg);
2654 
2655   ShenandoahWorkerScope scope(workers(),
2656                               ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(),
2657                               "concurrent reference update");
2658 
2659   try_inject_alloc_failure();
2660   op_updaterefs();
2661 }
2662 
2663 void ShenandoahHeap::entry_roots() {
2664   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_roots);
2665 
2666   static const char* msg = "Concurrent roots processing";
2667   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2668   EventMark em("%s", msg);
2669 
2670   ShenandoahWorkerScope scope(workers(),
2671                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
2672                               "concurrent root processing");
2673 
2674   try_inject_alloc_failure();
2675   op_roots();
2676 }
2677 
2678 void ShenandoahHeap::entry_cleanup() {
2679   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup);
2680 
2681   static const char* msg = "Concurrent cleanup";
2682   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2683   EventMark em("%s", msg);
2684 
2685   // This phase does not use workers, no need for setup
2686 
2687   try_inject_alloc_failure();
2688   op_cleanup();
2689 }
2690 
2691 void ShenandoahHeap::entry_reset() {
2692   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_reset);
2693 
2694   static const char* msg = "Concurrent reset";
2695   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2696   EventMark em("%s", msg);
2697 
2698   ShenandoahWorkerScope scope(workers(),
2699                               ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
2700                               "concurrent reset");
2701 
2702   try_inject_alloc_failure();
2703   op_reset();
2704 }
2705 
2706 void ShenandoahHeap::entry_preclean() {
2707   if (ShenandoahPreclean && process_references()) {
2708     static const char* msg = "Concurrent precleaning";
2709     GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2710     EventMark em("%s", msg);
2711 
2712     ShenandoahGCPhase conc_preclean(ShenandoahPhaseTimings::conc_preclean);
2713 
2714     ShenandoahWorkerScope scope(workers(),
2715                                 ShenandoahWorkerPolicy::calc_workers_for_conc_preclean(),
2716                                 "concurrent preclean",
2717                                 /* check_workers = */ false);
2718 
2719     try_inject_alloc_failure();
2720     op_preclean();
2721   }
2722 }
2723 
2724 void ShenandoahHeap::entry_traversal() {
2725   static const char* msg = "Concurrent traversal";
2726   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2727   EventMark em("%s", msg);
2728 
2729   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2730 
2731   ShenandoahWorkerScope scope(workers(),
2732                               ShenandoahWorkerPolicy::calc_workers_for_conc_traversal(),
2733                               "concurrent traversal");
2734 
2735   try_inject_alloc_failure();
2736   op_traversal();
2737 }
2738 
2739 void ShenandoahHeap::entry_uncommit(double shrink_before) {
2740   static const char *msg = "Concurrent uncommit";
2741   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2742   EventMark em("%s", msg);
2743 
2744   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_uncommit);
2745 
2746   op_uncommit(shrink_before);
2747 }
2748 
2749 void ShenandoahHeap::try_inject_alloc_failure() {
2750   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2751     _inject_alloc_failure.set();
2752     os::naked_short_sleep(1);
2753     if (cancelled_gc()) {
2754       log_info(gc)("Allocation failure was successfully injected");
2755     }
2756   }
2757 }
2758 
2759 bool ShenandoahHeap::should_inject_alloc_failure() {
2760   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2761 }
2762 
2763 void ShenandoahHeap::initialize_serviceability() {
2764   _memory_pool = new ShenandoahMemoryPool(this);
2765   _cycle_memory_manager.add_pool(_memory_pool);
2766   _stw_memory_manager.add_pool(_memory_pool);
2767 }
2768 
2769 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2770   GrowableArray<GCMemoryManager*> memory_managers(2);
2771   memory_managers.append(&_cycle_memory_manager);
2772   memory_managers.append(&_stw_memory_manager);
2773   return memory_managers;
2774 }
2775 
2776 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2777   GrowableArray<MemoryPool*> memory_pools(1);
2778   memory_pools.append(_memory_pool);
2779   return memory_pools;
2780 }
2781 
2782 MemoryUsage ShenandoahHeap::memory_usage() {
2783   return _memory_pool->get_memory_usage();
2784 }
2785 
2786 void ShenandoahHeap::enter_evacuation() {
2787   _oom_evac_handler.enter_evacuation();
2788 }
2789 
2790 void ShenandoahHeap::leave_evacuation() {
2791   _oom_evac_handler.leave_evacuation();
2792 }
2793 
2794 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2795   _heap(ShenandoahHeap::heap()),
2796   _index(0) {}
2797 
2798 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2799   _heap(heap),
2800   _index(0) {}
2801 
2802 void ShenandoahRegionIterator::reset() {
2803   _index = 0;
2804 }
2805 
2806 bool ShenandoahRegionIterator::has_next() const {
2807   return _index < _heap->num_regions();
2808 }
2809 
2810 char ShenandoahHeap::gc_state() const {
2811   return _gc_state.raw_value();
2812 }
2813 
2814 void ShenandoahHeap::deduplicate_string(oop str) {
2815   assert(java_lang_String::is_instance(str), "invariant");
2816 
2817   if (ShenandoahStringDedup::is_enabled()) {
2818     ShenandoahStringDedup::deduplicate(str);
2819   }
2820 }
2821 
2822 const char* ShenandoahHeap::init_mark_event_message() const {
2823   bool update_refs = has_forwarded_objects();
2824   bool proc_refs = process_references();
2825   bool unload_cls = unload_classes();
2826 
2827   if (update_refs && proc_refs && unload_cls) {
2828     return "Pause Init Mark (update refs) (process weakrefs) (unload classes)";
2829   } else if (update_refs && proc_refs) {
2830     return "Pause Init Mark (update refs) (process weakrefs)";
2831   } else if (update_refs && unload_cls) {
2832     return "Pause Init Mark (update refs) (unload classes)";
2833   } else if (proc_refs && unload_cls) {
2834     return "Pause Init Mark (process weakrefs) (unload classes)";
2835   } else if (update_refs) {
2836     return "Pause Init Mark (update refs)";
2837   } else if (proc_refs) {
2838     return "Pause Init Mark (process weakrefs)";
2839   } else if (unload_cls) {
2840     return "Pause Init Mark (unload classes)";
2841   } else {
2842     return "Pause Init Mark";
2843   }
2844 }
2845 
2846 const char* ShenandoahHeap::final_mark_event_message() const {
2847   bool update_refs = has_forwarded_objects();
2848   bool proc_refs = process_references();
2849   bool unload_cls = unload_classes();
2850 
2851   if (update_refs && proc_refs && unload_cls) {
2852     return "Pause Final Mark (update refs) (process weakrefs) (unload classes)";
2853   } else if (update_refs && proc_refs) {
2854     return "Pause Final Mark (update refs) (process weakrefs)";
2855   } else if (update_refs && unload_cls) {
2856     return "Pause Final Mark (update refs) (unload classes)";
2857   } else if (proc_refs && unload_cls) {
2858     return "Pause Final Mark (process weakrefs) (unload classes)";
2859   } else if (update_refs) {
2860     return "Pause Final Mark (update refs)";
2861   } else if (proc_refs) {
2862     return "Pause Final Mark (process weakrefs)";
2863   } else if (unload_cls) {
2864     return "Pause Final Mark (unload classes)";
2865   } else {
2866     return "Pause Final Mark";
2867   }
2868 }
2869 
2870 const char* ShenandoahHeap::conc_mark_event_message() const {
2871   bool update_refs = has_forwarded_objects();
2872   bool proc_refs = process_references();
2873   bool unload_cls = unload_classes();
2874 
2875   if (update_refs && proc_refs && unload_cls) {
2876     return "Concurrent marking (update refs) (process weakrefs) (unload classes)";
2877   } else if (update_refs && proc_refs) {
2878     return "Concurrent marking (update refs) (process weakrefs)";
2879   } else if (update_refs && unload_cls) {
2880     return "Concurrent marking (update refs) (unload classes)";
2881   } else if (proc_refs && unload_cls) {
2882     return "Concurrent marking (process weakrefs) (unload classes)";
2883   } else if (update_refs) {
2884     return "Concurrent marking (update refs)";
2885   } else if (proc_refs) {
2886     return "Concurrent marking (process weakrefs)";
2887   } else if (unload_cls) {
2888     return "Concurrent marking (unload classes)";
2889   } else {
2890     return "Concurrent marking";
2891   }
2892 }
2893 
2894 const char* ShenandoahHeap::degen_event_message(ShenandoahDegenPoint point) const {
2895   switch (point) {
2896     case _degenerated_unset:
2897       return "Pause Degenerated GC (<UNSET>)";
2898     case _degenerated_traversal:
2899       return "Pause Degenerated GC (Traversal)";
2900     case _degenerated_outside_cycle:
2901       return "Pause Degenerated GC (Outside of Cycle)";
2902     case _degenerated_mark:
2903       return "Pause Degenerated GC (Mark)";
2904     case _degenerated_evac:
2905       return "Pause Degenerated GC (Evacuation)";
2906     case _degenerated_updaterefs:
2907       return "Pause Degenerated GC (Update Refs)";
2908     default:
2909       ShouldNotReachHere();
2910       return "ERROR";
2911   }
2912 }
2913 
2914 jushort* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2915 #ifdef ASSERT
2916   assert(_liveness_cache != NULL, "sanity");
2917   assert(worker_id < _max_workers, "sanity");
2918   for (uint i = 0; i < num_regions(); i++) {
2919     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2920   }
2921 #endif
2922   return _liveness_cache[worker_id];
2923 }
2924 
2925 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2926   assert(worker_id < _max_workers, "sanity");
2927   assert(_liveness_cache != NULL, "sanity");
2928   jushort* ld = _liveness_cache[worker_id];
2929   for (uint i = 0; i < num_regions(); i++) {
2930     ShenandoahHeapRegion* r = get_region(i);
2931     jushort live = ld[i];
2932     if (live > 0) {
2933       r->increase_live_data_gc_words(live);
2934       ld[i] = 0;
2935     }
2936   }
2937 }