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