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