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