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