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