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