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